为什么这个 while 循环输出非常奇怪的东西

Why does this while loop output very strange things?

本文关键字:非常 输出 while 循环 为什么      更新时间:2023-10-16

我创建了一些代码,要求您输入变量量,然后要求您输入每个变量,然后将其存储在向量中。我遇到的问题是,当您输入不正确的内容时,它会要求您重试,它要么要求您输入变量一定次数,具体取决于您输入的字符,这真的很奇怪。我以为使用ssinput.clear();可以解决这个问题,但事实并非如此。

例如,如果我在下面的终端中输入这些内容:

Please input variable 1: a
 ERROR, PLEASE ENTER ONLY VALID SYMBOLS
---------------------
Please input variable 1: 1
Please input variable 1: 3
Please input variable 1: 5
Please input variable 2: 1
Please input variable 3: 4
Please input variable 4: 3
Please input variable 5: 3

总的来说,它非常零星和奇怪。我的代码在下面。

#include <iostream>
#include <string>
#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 = 5;
vector<double> userNums;
double input = 0;
string checkInput = "";
bool valid = false;
stringstream sstotVar;


    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);
            stringstream ssinput(checkInput);
            ssinput >> input;
            if (ssinput.fail()) {
                inputErrorMessage();
                valid = false;
            }
            if (valid == true) {
                userNums.push_back(input);
                varNum++;
            }
                ssinput.clear();
            }
        }
}

问题出在这些陈述中

vector <double> userNums;
double input = 0;

ssinput >> input;
if (ssinput.fail())

检查输入是否包含十进制数字。 这是您不能输入字符的方式。

看看这个。 编译并运行...

#include <iostream>
#include <string>
#include <vector>
#include <sstream>
using namespace std;
void inputErrorMessage(){
    cout << "n ERROR, PLEASE ENTER ONLY VALID SYMBOLS n";
    cout << "--------------------- n";
}

int main(void) {
// Declare the variables, vectors, etc.
int varNum = 1;
int totVar = 5;
vector<string> userNums;
string input = "";
string checkInput = "";
bool valid = false;
stringstream sstotVar;


    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);
            stringstream ssinput(checkInput);
            ssinput >> input;
            if (ssinput.fail()) {
                inputErrorMessage();
                valid = false;
            }
            if (valid == true) {
                userNums.push_back(input);
               varNum++;
            }
                ssinput.clear();
            } 
        }
}