C++,cin,直到使用while循环在线上不再有输入为止

C++, cin until no more input on line using a while loop

本文关键字:不再 在线 输入 while cin C++ 循环      更新时间:2023-10-16

我的C++程序有问题。我重新格式化并显示用户在控制台中输入的单词。如果用户输入:嗨,我是bob。在控制台中输入bob后,用户将按enter键。我将重新格式化并以新格式重新打印。问题是,在输入控制台行上的所有单词之前,我不想显示更多输入的消息。我的当前循环要么在每个单词后面显示输入请求,要么根本不显示。这取决于我是否包含提示。我需要让while循环处理每个单词,并输出它,在最后一个单词后停止。什么是布尔参数?我将包含我的代码以供参考。

int _tmain(int argc, _TCHAR* argv[])
{
    int b;
    string input;
    string output ;
    int check = 1;
    while (check){
        cout << "Enter in one or more words to be output in ROT13: " << endl;
        cin >> input;
        while(my issue is here){
            const char *word = input.c_str();
            for (int i = 0; i < input.length(); i++){
                b = (int)word[i];
                if (b > 96){
                    if (b >= 110){
                        b = b - 13;
                    }
                    else {
                        b = b + 13;
                    }
                    output += ((char)b);
                }
                else
                {
                    if (b >= 78){
                        b = b - 13;
                    }
                    else {
                        b = b + 13;
                    }
                    output += ((char)b);
                }



            } 
            cout << output << endl;
            output = "";
            cin >> input;
        }
            check = 0;
    }
    return 0;
}

如果没有更多的行可供输入,cin函数将返回false。您可以执行以下操作以读取直到输入结束,或者如果您将cin重定向到从文件读取,则可以执行eof。

int a;
while(cin >> a){
    //Your loop body
}

您可以用以下行替换整个while循环:

std::getline(std::cin, input);  // where input is a std::string

然后在这一行之后重新格式化。