Zain Lab Report 3
Zain Lab Report 3
Lab Report 03
Theory:
1. Getline function.
2. Increment Operator.
3. Classes and Objects.
Getline Function:
The getline function is a built in function in the standard C++ library that is
often used to take input in a better and more professional way than the cin function because
the cin function takes spaces as an enter and doesnt let you write a whole line in the input
terminal while the getline function allows you to read multiple lines of strings from the imput
stream. e.g
We initialize a variable.
int a;
getline(cin,a);
This is the syntax of how the getline function can be used in our
programs.
Increment Operator:
Increment operators are used to increase the value of a variable by 1 , It
works in 2 way ,either increasing value before assigning or after assigning. Its syntax can be as
shown:
int a;
a++; for post increment
++a for pre increment
Post increment increases the value after assiging it the variable and pre increment increases it
before assigning it to the variable.
Lab work:
Code to use Getline function:
#include <iostream> //header file
using namespace std;
int main() {
string ans;
cout << "What do you like man? ";
//getline(cin,ans);
cin >> ans;
cout << ans;
return 0;
}
In this function we use cin function and in the ouput we can see that it only registers the string
before the space.
Output:
Output:
Output:
For pre increment:
#include <iostream> //header file
using namespace std;
int main() {
int a, b;
a = 1;
b = ++a;
cout << "a= " << a << endl << "b= " << b;
return 0;
}
Output:
int main() {
header headobj;
headobj.code_1();
headobj.code_2();
headobj.code_3();
headobj.code_4();
return 0;
}
Output:
Getline Solution:
Adding >> ws after cin in the syntax of getline resolves the faced problem .
#include <iostream>
using namespace std;
int main() {
string ans;
int a;
cout << "Type a number: ";
cin >> a;
cout << "How is the weather today? ";
getline(cin >> ws, ans);
cout << ans << endl;
cout << "Its " << a << " degrees today.";
return 0;
}
Output: