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

时间:2017-02-11 19:39:55

标签: c++ for-loop while-loop

我创建了一些代码,要求您输入可变数量,然后要求您输入每个变量,然后将其存储在矢量中。我遇到的问题是,当你输入不正确的东西,并要求你再试一次时,它会要求你输入变量一定次数,这取决于你输入的字符,这真的很奇怪。我认为使用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();

            }
        }
}

1 个答案:

答案 0 :(得分:0)

问题在于这些陈述

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();

            } 
        }
}