如何在用户按enter键时停止cin循环? 这是我现在的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') //提示用户循环 字符预输入; 做{ //用输入填充向量 矢量用户输入; cout(预输入){ 如果(预输入=='Q'| |预输入=='Q')中断; int输入=(int)预输入-'0'; 用户输入。推回(输入); } //与行同步的和数组# 整数和[10]={0}; //计算发生额 对于(向量::迭代器i=userInputs.begin();i!=userInputs.end();i++){ int currInput=*i; 对于(int numLine=0;numLine

如何在用户按enter键时停止cin循环? 这是我现在的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') //提示用户循环 字符预输入; 做{ //用输入填充向量 矢量用户输入; cout(预输入){ 如果(预输入=='Q'| |预输入=='Q')中断; int输入=(int)预输入-'0'; 用户输入。推回(输入); } //与行同步的和数组# 整数和[10]={0}; //计算发生额 对于(向量::迭代器i=userInputs.begin();i!=userInputs.end();i++){ int currInput=*i; 对于(int numLine=0;numLine,c++,loops,while-loop,user-input,cin,C++,Loops,While Loop,User Input,Cin,使用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.pus

使用
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);
}