You are not logged in. Please login at www.codechef.com to post your questions!

×

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;
}

asked 29 Mar '17, 14:58

horcrux2301's gravatar image

4★horcrux2301
17117
accept rate: 5%


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.

link

answered 29 Mar '17, 15:08

bansal1232's gravatar image

5★bansal1232
2.8k1419
accept rate: 16%

1

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.!

(29 Mar '17, 15:41) horcrux23014★

@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.

link

answered 29 Mar '17, 15:53

bansal1232's gravatar image

5★bansal1232
2.8k1419
accept rate: 16%

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

link

answered 29 Mar '17, 18:13

horcrux2301's gravatar image

4★horcrux2301
17117
accept rate: 5%

toggle preview
Preview

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Markdown Basics

  • *italic* or _italic_
  • **bold** or __bold__
  • link:[text](http://url.com/ "title")
  • image?![alt text](/path/img.jpg "title")
  • numbered list: 1. Foo 2. Bar
  • to add a line break simply add two spaces to where you would like the new line to be.
  • basic HTML tags are also supported
  • mathemetical formulas in Latex between $ symbol

Question tags:

×1,912
×643

question asked: 29 Mar '17, 14:58

question was seen: 496 times

last updated: 29 Mar '17, 18:13