所以最近我一直在尝试学习C++,并且一直在关注我朋友推荐的这本书,这是C++ Primer第5版,里面有以下代码。
const string hexdigits = "0123456789ABCDEF"; // possible hex digits
cout << "Enter a series of numbers between 0 and 15"
<< " separated by spaces. Hit ENTER when finished: "
<< endl;
string result; // will hold the resulting hexify’d string
string::size_type n; // hold numbers from the input
while (cin >> n)
if (n < hexdigits.size()) // ignore invalid input
result += hexdigits[n]; // fetch the indicated hex digit
cout << "Your hex number is: " << result << endl;
我一直在绞尽脑汁,试图弄清楚如何让它发挥作用。
所以我在这段代码中遇到的两个问题都与“
" 或以 cin 结束行。
我如何使“完成后按回车键”工作。这样当我执行 2 12 3 4 ENTER 时,它就会从 while 循环中中断。
我如何检查,以便我在单击 Enter 时所做的第一件事是否也不进入循环。 (基本上我如何检查输入的第一件事是否是一个新行以及是否要跳过整个过程)
也许我问的就是这么简单。但我发誓我无法理解它。
我尝试过诸如 cin.peek() 和 cin.get() 之类的东西,但是在它们之后继续阅读会更复杂。
使用第一个选项,我尝试过:
cin >> n;
while (n < hexdigits.size()) {
result += hexdigits[n];
if (cin.peek() == '\n') {
break;
}
else {
cin >> n; // Read the actual input if not ENTER
}
}
这可行,但我认为它很丑陋,我想知道是否还有其他方法可以做事。
感谢所有阅读并花时间回复的人:)。
你的解决方案是正确的,而且一点也不难看,尽管最后的
else
是不必要的(如果我们从循环中中断,无论如何我们都不会到达else
部分)。您可以进一步美化您的代码,例如,使用 do...while
循环代替(这样您就不必使用 cin >> n;
两次,而只需在循环开始时使用一次),但这是一个小细节。
无法直接检索
Enter
作为换行符的原因是因为流执行一些内部解析,这会导致(以及其他操作)在消除前导空格的过程中在输入末尾删除换行符。这显然就是 operator >>
在标准输入流中的实现方式。您可以在此处阅读更多相关信息。