×

# unable to get input the proper way.

 0 In c++, I want to input a string after I input a number. This is my code. Why string s doesn't get any input? What is the correct way of doing it? asked 13 Feb '17, 22:17 4★ayush933 97●5 accept rate: 0%

 1 The problem is that you are not flushing the newline ('\n') character after cin>> statement. so you must need to flush the newline character out of the buffer in between. You can do it by using cin.ignore(). This happens because the >> operator leaves a newline \n character in the input buffer which which be taken by getline() prior to reading your next input. Click here to see my code. answered 13 Feb '17, 23:21 2.8k●1●4●19 accept rate: 16% Why doesn't this happen when we try to input 2 int which are on different lines? http://ideone.com/464EAy This works but the previous one doesn't. (13 Feb '17, 23:28) ayush9334★
 2 First of all you have to understand how both cin>> and getline() works. cin>> starts working by first eliminating all white spaces and newline character. That's why input like in one line  45 98 65  will be taken as 3 input. Why?, because cin>> will automatically terminate and stop taking input after getting any white space or newline character. getline works differently. It takes any character at starting whether it is white space or newline. That's why i had to include cin.ignore() to eliminate newline character. Another property of getline is it will only terminate after getting newline('\n') character. answered 13 Feb '17, 23:51 2.8k●1●4●19 accept rate: 16% 1 Exactly what I had to say!! Well explained! :) (13 Feb '17, 23:54) Nice Explanation. Thanks. (14 Feb '17, 02:01) ayush9334★
 0 Correct way-  #include #include using namespace std; int main() { int b; string s; cin>>b; cin>>s; cout<>s will stop at the first whitespace it encounters (13 Feb '17, 23:33)
 toggle preview community wiki:
Preview

By Email:

Markdown Basics

• *italic* or _italic_
• **bold** or __bold__
• 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:

×170

question asked: 13 Feb '17, 22:17

question was seen: 593 times

last updated: 26 Dec '17, 10:15