如何在用户点击回车键时使cin循环停止
How can I get a cin loop to stop upon the user hitting enter?
这是我现在的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);
}
相关文章:
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- 在 std::getline 和 std::cin 期间卡在循环中
- C++ cin.ignore() 跳过循环
- 而循环跳过 cin.getline() 对于 C 字符串
- 当输入在带有空格的单行中给出时,cin 如何在 while 循环中工作?
- :CIN 不断打印用户在每次循环后输入的内容
- 输入 ctrl + x 后如何再次 cin (cin<<x) 循环(cin 一个结构)
- cin语句在循环的第三次迭代中被跳过
- 在循环中使用 cin.get() 输入字符串
- 尝试将未知数量的字符串推送到向量中,但我的 cin 循环没有终止
- 另一个C CIN循环问题
- CIN循环永远不会终止
- 用cin循环时使用C++do
- 如何在用户点击回车键时使cin循环停止
- C++ - 使用 cin 循环运行 while 后,程序不会再次接受输入
- 读取所有数据后进行无限cin循环
- while(cin)循环双显示
- 在 C++ 中按 ctrl+D 在 (cin>>i) 循环中时发生了什么?
- std::cin循环,即使我调用ignore()和clear()
- 退出带有回车符的 while(cin >> s) 循环