所以,我环顾四周,无法弄清楚在我的 While 循环中 cin 发生了什么.我正在阅读《C++ Primer》(第 5 版)这本书,我注意到在其中一个练习中,我无法使用 cin 来抓取字符串,除非它不终止 while 循环.我只使用 getline() 解决了这个问题.
So, I've looked around and haven't been able to figure out what's going on with cin during my While loop. I'm working through the book C++ Primer (5th edition) and I noticed that during one of the exercises I couldn't use cin to grab strings without it not terminating the while loop. I fixed this issue by just using getline().
当前练习的目标是要求用户输入 0 - 15 的值,并将该数字转换为Hex Equivelant"(其中 0 = 1, 1 = 2, 2 = 3, ..., 10 = A, 11 = B).我尝试在没有这本书的情况下这样做并失败了,但随后开始质疑书中的代码.这是书中的代码:
The goal of the current exercise is to ask for user input from the values of 0 - 15, and converting that number into it's "Hex Equivelant" (Where 0 = 1, 1 = 2, 2 = 3, ... , 10 = A, 11 = B). I tried doing this without the book and failed, but then started questioning the code in the book. Here's the code in the book:
//Note: <iostream> and <string> have been included. using namespace std is used
const string hexdigits = "0123456789ABCDEF";
cout << "Enter a series of numbers between 0 and 15"
<< " separated by spaces. Hit ENTER when finished: "
<< endl;
string result;
string::size_type n;
while(cin >> n)
if (n < hexdigits.size())
result += hexdigits[n];
cout << "Your hex number is: " << result << endl;
如果我要运行这段代码,它永远不会在没有输入任何代码的情况下按 Enter 键后终止 while 循环(基本上是输入我认为的空格?).
If I were to run this code, it would never terminate the while loop after hitting enter without entering any code (essentially giving the input of whitespace I would think?).
我来这里有两个原因:
1) 为什么这段代码不起作用?2)我希望朝着正确的方向轻推,但不是如何正确执行此代码的答案
1) Why does this code not work? 2) I would appreciate a nudge in the right direction, but not the answer to how to get this code to execute correctly
如果我不能在不妥协原因 2 的情况下获得原因 1,我宁愿让原因 1 得到满足.
If I can't receive reason 1 without compromising reason 2, I would much rather have reason 1 be fulfilled.
快速抱歉,我使用的是 Visual Studio 2012
Quick- I apologize, I'm using Visual Studio 2012
按 Enter 会产生 CR 或 LF 或两者,具体取决于您的平台.这是一个有效的输入,因此满足继续 while 循环的条件.您需要在输入的开头明确测试这些字符,或者使用 Ctrl-C 来跳出循环.
Hitting Enter produces either a CR or LF or both, depending on your platform. This is a valid input so satisfies the condition to continue the while loop. You will need to either explicitly test for these characters at the beginning of your input or use Ctrl-C to break out of the loop.
作为一个可读性问题,我会在循环中需要的代码周围加上大括号.您拥有的是有效的 C++,因为没有大括号 while 将在下一个语句上循环,并且整个 if 条件是单个语句.即使在单行循环中,现在也练习将它们放入,这样您将来就可以省去一些麻烦的调试工作.
As a readability issue, I would include braces around the code that you want in the loop. What you have there is valid C++ since without braces the while will loop on the next statement and the whole if conditional is a single statement. Practice putting them in now even on single line loops and you'll save yourself some headache debugging in the future.
这篇关于Cin in a while 循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!