这里是我的C++代码现在:如何获取cin循环以停止用户点击输入?
// 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中。 按Enter键后,循环需要执行while(cin >> preInput){}语句下面的所有代码,清除userInput向量,然后重复,直到输入字符Q.这不是发生了什么事。循环当前写入的方式,该程序需要用户输入,直到用户点击Q,输入本质上什么都不做。我需要代码在用户输入时执行。我一直在玩这个有一段时间,但我不太熟悉通过cin通过char将数据传输到矢量中,所以我不知道如何做到这一点...任何人都可以指向正确的方向吗?
会改变cin >> preInput到getline工作吗?或者,这会试图将值“... 123”作为一个赋值放入char preInput中?我需要矢量分别接收数字,而不是将所有数字合并为一个元素。重申一下,如果用户输入“123”userInputs [0]应该是1,userInputs [1]应该是2 ...等等。
本质上,唯一需要改变的是while(cin >> preInput){}循环在用户输入时必须中断。