0

I want to write a program which reads in a line and a character and then print them together iterally. This is my code:

#include <string>
#include <iostream>
using namespace std;
int main() {
  string s;
  string a;
  while (getline(cin,s)) {
    cin>>a;
    cout<<s<<a<<endl;
  }
}

The first time I input:"abc d" as a line and then "a" as a character and the output is "abc da". But then I input "abc d" again, it immediately output "abc" without waiting for me to input "a" and then output "abc da". Where is my code wrong?

Yihan Zhou
  • 47
  • 7

1 Answers1

0

After the cin>>a; there is still a newline in the buffer which is then read by the getline(). To avoid this you need to flush the newline out of the buffer. This can be achieved by calling cin.ignore() and in some cases cin.sync(), although I am not sure of the exact functionality of the cin.sync() function.

cowdrool
  • 314
  • 1
  • 6