【发布时间】:2013-10-10 23:35:59
【问题描述】:
所以,我环顾四周,无法弄清楚在我的 While 循环中 cin 发生了什么。我正在阅读 C++ Primer(第 5 版)一书,我注意到在其中一个练习中,如果不终止 while 循环,我就无法使用 cin 来抓取字符串。我只使用 getline() 解决了这个问题。
当前练习的目标是要求用户输入 0 - 15 的值,并将该数字转换为“十六进制等值”(其中 0 = 1, 1 = 2, 2 = 3, ... , 10 = A, 11 = B)。我尝试在没有书的情况下这样做,但失败了,但随后开始质疑书中的代码。这是书中的代码:
//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;
如果我要运行这段代码,它永远不会在不输入任何代码的情况下按回车键终止 while 循环(我认为本质上是输入空格?)。
我来这里有两个原因:
1) 为什么这段代码不起作用? 2)我会很感激朝着正确的方向轻推,但不是如何让这段代码正确执行的答案
如果我不能在不妥协原因 2 的情况下接受原因 1,我宁愿满足原因 1。
快速编辑:抱歉,我使用的是 Visual Studio 2012
【问题讨论】:
标签: c++ while-loop cin