我有一个程序可以做三件事。询问你想要多少个变量,要求你输入每个变量,然后将其存储在一个向量中。我已经放了一些代码来检查您的输入是否正确,如果不正确,请重新循环代码以询问您的变量。我遇到的问题是,当你在第二个变量周围输入任何东西时,它会要求你无限次地尝试。无论你输入什么内容,为什么while循环都输出相同的内容?
举例来说,如果我输入这些值输入:
Variable amount: 5
Please input variable 1: 8
Please input variable 2: 8
ERROR, PLEASE ENTER ONLY VALID SYMBOLS
---------------------
Please input variable 2:
这样可以保证输出ERROR, PLEASE ENTER ONLY VALID SYMBOLS
一遍又一遍,不管你输入的内容。代码在下面,如果你对这个问题有更好的名字,请告诉我。 (我真的不知道该怎么称呼它)
#include <iostream>
#include <cmath>
#include <string>
#include <algorithm>
#include <vector>
#include <sstream>
using namespace std;
int inputErrorMessage()
{
cout << "\n ERROR, PLEASE ENTER ONLY VALID SYMBOLS \n";
cout << "--------------------- \n";
return 0;
}
int main()
{
// Declare the variables, vectors, etc.
int varNum = 1;
int totVar = 0;
int choice = 0;
vector<int> userNums;
double input = 0;
string checktotVar = "";
string checkInput = "";
string sym = "";
bool valid = false;
stringstream sstotVar;
stringstream ssinput;
if (choice != 6) {
while (!valid) {
valid = true;
// Ask user for how many variables they want then record it
cout << "Variable amount: ";
getline(cin, checktotVar);
sstotVar << checktotVar;
sstotVar >> totVar;
if (sstotVar.fail() || totVar <= 0) {
inputErrorMessage();
valid = false;
sstotVar.clear();
sstotVar.ignore();
}
}
valid = false;
while (!valid) {
valid = true;
// Ask the user for each variable, then record it into the array
for (int i = 0; i < totVar; ++i) {
cout << "Please input variable " << varNum << ": ";
getline(cin, checkInput);
ssinput << checkInput;
ssinput >> input;
if (ssinput.fail()) {
inputErrorMessage();
valid = false;
ssinput.clear();
ssinput.ignore();
}
if (valid == true) {
userNums.push_back(input);
varNum++;
}
}
}
}
}
我建议你学习如何使用你的调试器。请在将来除了解决这个问题之外,还会帮助你。 – Fureeish
另外,请注意,您不需要在函数的开头部分声明所有变量。代码通常更容易阅读和理解变量声明接近它们的使用位置。 –