Facing problem with getline in cpp

I don’t know but why i am facing trouble with a simple getline standard library function. If I use getline then my code do not work as it is supposed to, even you can check by just using getline inside test case, what it will do is that it will skip output of test case 1 and answer of test case 1 will print for test case 2 and so on and so we will lose output of last test case. I even tried using cin.ignore (as mentioned on stack overflow) but still there was ambiguity.

Try using getchar() before getline.

Use this…
getline(cin,a);
while(a.length()==0){
getline(cin,a);
}

What I believe I understanding of problem is more important than solution. So instead of spoon feeding solution to you directly, I will explain you the issue and will guide you a little bit about solution.

If you mix getline and scanning integer then it might create issues. Let me explain how.
Its very simple , you just need to understand how it works.

Problem :

Suppose the input format is

Integer\n
One line of string input\n
Integer\n

… And so on.
Then when you scan integer using cin or scanf then it will scan the integer till it reads “\n” or " " ( blank space)
Issue will be there when there is one \n char after integer.
And it will stop before “\n”
Now when you try to read using getline you will get blank string in input because getline will directly get “\n” in input and it will stop reading.

Whereas getline will also scan till it reads “\n”
And will stop after \n.

Solution :

Add extra getline whenever it’s required according to input format and it will start working as you want it to.

Now that you understand the actual issue, you can easily resolve it by putting extra getline(); whenever required.

Just remember where will you have extra newline chars in input.

PS : correct me if I am wrong anywhere. These things are purely based on my experience and it always works for me. I am 99.9999% sure about this. :stuck_out_tongue:

2 Likes

I faced the same problem yesterday , you just have to write cin>>ws above the loop.
ex- cin>>ws; while(testcase--){ string s; getline (cin, s); }
(for explanation) link - getline not working in loop.