#include <iostream>
#include<string>
using namespace std;int main()
{
int T, i;
string A, B;
cin >> T;
for(i=0; i<T; i++)
{
getline(cin, A);
getline(cin, B);
cout << A << endl;
cout << B << endl;
}
system("pause");
return 0;
}
When working with strings, why does it skip line for string B for the first repetition. For instance,
Input
3
apple
banana
orange
Jackfruit
Grapes
Output
apple
banana
orange
Jackfruit
Even before I can type for the input of string B, it skips line and prints the output for string A. How can I prevent this?
Asked by: Abhinav_Lugun on April 7, 2019, 6:34 p.m. Last updated on April 7, 2019, 6:34 p.m.
It is actually skipping for string A, not B. This is because getline() takes input unless it encounters a newline character ("\n" or when we press enter). So when it completes scanning the value for T, it goes to the new line to scan the value of A, but on getting that new line the first getline gets skipped and the value of A gets assigned to B.
To make it work, just add a cin>>ch after cin>>T (outside loop) where ch is of type character. It accepts the newline character after T. Now, it works!