Why is following piece of Code not working?

I am trying to input a string with spaces and after that 2 integers which are entered in the next line. I am using the following code. But this is not working.!

#include <iostream>
#include <string>
using namespace std;  
int main()
{
int test;
cin >> test;
while(test--)
{
string str;
int a,b;
getline(cin,str);
cin >> a >> b;
cout << str << " " << a << " " << b << " " << endl;
}
return 0;
}

Here the null character of test case “test” has been appending in the getline() function. So you have to pass the Null character before using getline(). You can simply achieve this by using getchar() function that can take Null character before passing to getline() function. See my code, i just add only getchar() function.

1 Like

@horcrux2301 I am talking about that null character which comes into picture when you hit Enter key button or start new line. These are characters which still remain in execution and must be interpreted before taking any real integer/float/string etc values.

Now the question is Why? we don’t need to use getchar() function when we take the input from cin>> or scanf()? The answer is scanf() and cin>> starts taking the input after removing any white spaces or null character in between them. But when you use getline() it will accept any character whether it is white-space or NULL.

I hope you will get the concept other-wise you can also prove it by printing the character that getchar() has been taking in this example.

3 Likes

Thank you taking out the time to explain that @bansal1232 . Appreciate it.!!!

So the geline() function in my code was reading that null character first?
Also test is an integer. Where did that null character come from. My understanding is that it should be a string.!

1 Like