-2

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() .

Shibli
  • 5,879
  • 13
  • 62
  • 126
varun sharma
  • 1
  • 1
  • 2
  • 1
    Possible duplicate of [Using getline(cin, s) after cin](http://stackoverflow.com/questions/5739937/using-getlinecin-s-after-cin) – Shibli Apr 09 '17 at 21:49

1 Answers1

-1

Try:

cin.ignore(); 

then

getline(cin, s2);
cin.ignore();

This will flush the input stream.

BusyProgrammer
  • 2,783
  • 5
  • 18
  • 31
msfs
  • 11
  • 2