简体   繁体   English

试图用C ++读取一行键盘输入

[英]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. 我试图用C ++完成一项大学任务,并且在应该是一个非常基本的操作时遇到麻烦。 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. 我理解,最后一行应该读取输入缓冲区(在本例中为cin)并将字符存储在't'字符串中,直到它到达新行字符,然后继续程序流程。

However, when I run my code in XCode, it just sort of jumps over the getline function and treats 't' as an empty string. 但是,当我在XCode中运行我的代码时,它只是跳过getline函数并将't'视为空字符串。

What's going on? 这是怎么回事? I tried using cin >> t but that just read characters forever - Why cant I get this to behave? 我尝试使用cin >> t但这只是永远读取字符 - 为什么我不能这样做?

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 . 显然是跳过输入操作的原因很可能(这意味着,忽略了一个bugsy XCode IDE的可能特性),你之前已经执行了一些输入并在输入缓冲区中留下了一个换行符

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. 一种简单的方法是始终将getline用于string ,然后如果要将数字规范转换为数字类型,则使用例如istringstream

Cheers & hth., 干杯&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. 这听起来像Xcode运行程序的方式有问题。 Try running your program directly from the terminal, and see if this is sufficient to fix your issue. 尝试直接从终端运行程序,看看这是否足以解决您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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