如何在用户点击回车键时使cin循环停止

How can I get a cin loop to stop upon the user hitting enter?

本文关键字:cin 循环 回车 用户      更新时间:2023-10-16

这是我现在的C++代码:

// Prompt user loop
char preInput;
do {
    // Fill the vector with inputs
    vector<int> userInputs;
    cout << "Input a set of digits: " << endl;
    while(cin>>preInput){
        if(preInput == 'Q' || preInput == 'q') break;
        int input = (int) preInput - '0';
        userInputs.push_back(input);
    }       
    // array of sums sync'd with line #
    int sums[10] = {0};
    // Calculate sums of occurance
    for(vector<int>::iterator i = userInputs.begin(); i != userInputs.end(); i++){
        int currInput = *i;
        for(int numLine = 0; numLine < lines.size(); numLine++){
            sums[numLine] += lineOccurances[numLine][currInput];
        }
    }
    int lineWithMax = 0;
    for(int i = 0; i < 10; i ++)        
        if(sums[i] > sums[lineWithMax]) lineWithMax = i;
    cout << lines[lineWithMax] << endl;
    // Clear vector
    userInputs.clear();
} while (preInput != 'Q' && preInput != 'q')

不要担心循环的功能,我只需要它以某种方式运行。如果用户键入"123",则循环应将字符1,2,3作为单独的元素加载到userInputs中。点击回车后,循环需要执行while(cin>>preInput){}语句下面的所有代码,清除userInput向量,然后重复,直到输入字符Q。事实并非如此。按照目前编写循环的方式,程序接受用户输入,直到用户点击Q,输入基本上什么都不做。每当用户点击回车键时,我需要执行代码。我已经玩了一段时间了,但我不太熟悉通过cin将数据通过char转换为向量,所以我不知道如何做到这一点。。。有人能给我指正确的方向吗?

将cin>>preInput更改为getline是否有效?或者,这种价值观的尝试会说。。。将"123"作为一个赋值输入到char preInput中?我需要向量来单独接收数字,而不是作为一个元素一起接收。重申一下,如果用户输入"123",则userInputs[0]应为1,userInputs[1]应为2…依此类推

本质上,唯一需要更改的是,当用户点击enter时,while(cin>>preInput){}循环必须中断。

使用getline读取一行,然后使用istringstream拆分该行。

std::string line;
std::getline(std::cin, line);
std::istringstream iss(line);
while(iss>>preInput){
    if(preInput == 'Q' || preInput == 'q') break;
    int input = (int) preInput - '0';
    userInputs.push_back(input);
}

或者,由于一次只看一个字符,所以可以直接看字符串中的字符。

for (char c : line)
{
    if (c == 'Q' || c == 'q') break;
    int input = c - '0';
    userInputs.push_back(input);
}