如何在循环延续条件下区分数字 10 和 'n'?

How to Differentiate Number 10 from ' ' in a Loop-Continuation Condition?

本文关键字:数字 循环 延续 条件下区      更新时间:2023-10-16

我有以下代码部分:

cout << "Enter a series of integers: ";
cin >> integer;
while (integer != 'n')
{
    cout << ...
    cin >> integer;
} // end while

如果用户输入10,我的循环将中断,因为数字10=十进制的'\n'值。

我该如何解决这个问题?

谢谢,

您尝试的代码不起作用,因为操作cin >> integer提取数字并将其转换为int。它无法区分行尾的位置。

相反,您应该读取一整行,然后从该行中提取整数,例如:

std::string s;
std::getline(std::cin, s);
std::istringstream iss(s);
int integer;
while ( iss >> integer )
{
    // do something with integer
}

考虑先将用户的输入读取到std::string
如果不是换行符,请转换为int并完成您的工作。

#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
int main(){
    std::string integer;
    cout << "Enter a series of integers: ";
    cin >> integer;
    while (integer != "x") //<- can't be whitespace
    {
        cout << atoi(integer.c_str()) << std::endl;
        cin >> integer;
    }
}

默认情况下,输入流将跳过任何空白,包括换行符。换句话说,除非有人输入"10",否则输入值中永远不会有10。处理输入的一般方法是读取,直到读取失败(例如,由于EOF):

while(cin >> value)
{
    // use value here
}
// failure, EOF or garbage on input

请注意,在之后读取任何其他内容之前,您必须先对流进行cin.clear()处理,并且其中仍然有垃圾,您必须对其进行cin.ignore(..)处理。也许您想使用getline()来使用基于行的输入,然后只需检查结果字符串是否为空,或者(尝试)将其解析为整数,否则。

#include <iostream>
int main(void)
{
int integer = 0;
std::cout << "Enter a series of integers: ";
std::cin >> integer;
while (integer != 'n' || integer == 10) {// **this will not work, it's wrong!**
    std::cout << integer << std::endl;
    std::cin >> integer;
}//end while
return 0; 
}