按回车键后,程序没有输出任何结果.为什么会这样

After I have pressed ENTER, the program did not output any results. Why is this happening?

本文关键字:结果 任何 为什么 输出 回车 程序      更新时间:2023-10-16

我是C++新手。我在网上看到了这个代码。按回车键后,程序没有输出任何结果。 为什么会这样?有人可以帮我吗?提前感谢您的任何帮助!

int main(){
    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;
}

我输入了:

12 0 5 15 8 15

输入循环将继续读取整数,直到输入流关闭,或者遇到无法解析为整数的内容。 每个值由任何空格(包括换行符)分隔。

如果你想为每一输入输出新的东西,你可以使用 std::getline 首先读取字符行,然后从std::istringstream读取:

string line;
while( getline( cin, line ) )
{
    istringstream iss( line );
    string result;
    string::size_type n;
    while(iss >> n){
        if(n < hexdigits.size()){
            result += hexdigits[n];
        }
    }
    cout << "your hex number is: " << result << endl;
}