简体   繁体   中英

Trying to Read a Line of Keyboard Input in C++

I mam trying to complete a college assignment in C++ and am having trouble with what should be a very basic operation. I am trying to read a string of characters from the keyboard. This is the relevant code:

  string t;
  cout << endl << "Enter title to search for: ";
  getline(cin, t, '\n');  

I understand, that the last line is supposed to read the input buffer (cin , in this instance) and store the character in the 't' string until it reaches a new line character and then continue the program flow.

However, when I run my code in XCode, it just sort of jumps over the getline function and treats 't' as an empty string.

What's going on? I tried using cin >> t but that just read characters forever - Why cant I get this to behave?

The reason that the input operation apparently is skipped, is most probably (that means, ignoring possible peculiarities of a bugsy XCode IDE) that you have performed some input earlier and left a newline in the input buffer .

To fix that, make sure that you have emptied the input buffer after each input operation that logically should consume a line of input.

One easy way is to always use getline into a string , and then use eg an istringstream if you want to convert a number specification to number type.

Cheers & hth.,

From the docs page it looks like you want

cin.getline(t,256,'\n');

or something similar.

This sounds like an issue with the way Xcode is running your program. Try running your program directly from the terminal, and see if this is sufficient to fix your issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM