I have a simple program to output sum of 2 integers, double and concatenate 2 strings. Here is my code that works fine:
int main() {
int i = 4;
double d = 4.0;
string s = "HackerRank ";
// Declare second integer, double, and String variables.
int i2;
double d2;
string s2;
// Read and save an integer, double, and String to your variables.
cin>>i2;
cin>>d2;
cin.get();
getline(cin, s2);
// Print the sum of both integer variables on a new line.
cout<<i+i2<<endl;
// Print the sum of the double variables on a new line.
cout<< setprecision(1)<<fixed<<d+d2<<endl;
// Concatenate and print the String variables on a new line
// The 's' variable above should be printed first.
cout<<s+s2;
return 0;
}
However if I remove the statement cin.get()
the input of the string s2
doesn't take place. Why is this so??
I think this has something to do with the streams/input buffers and the inner coding of getline(cin, ). Moreover the program gives an error when I use cin.getline()
.