Stringstream不会输出额外的变量?

时间:2017-03-11 22:11:53

标签: c++ stringstream

我有这个程序读取用户输入的整数。程序首先将输入作为字符串读取,然后我使用字符串流将其转换为整数。问题是字符串流只输出第一个输入。因此,在第一次输入后,userNumInput仍然是第一个输入,因为它没有读取任何其他内容。

    stringstream so;
    string userInput;
    int userNumInput = 0;

    while(userInput != "done") {
        cout << "Enter an integer or type done: ";
        cin >> userInput;
        if (isdigit(userInput[0])){
            so << userInput; //here is the problem
            so >> userNumInput; 
            userVector.push_back(userNumInput);
            so.str("");
        }
    }

1 个答案:

答案 0 :(得分:0)

vector<int> userVector;
stringstream so;
string userInput;
int userNumInput = 0;

while (userInput != "done") {
    cout << "Enter an integer or type done: ";
    cin >> userInput;
    if (isdigit(userInput[0])) {
        so << userInput; //here is the problem
        so >> userNumInput;
        userVector.push_back(userNumInput);
        so.str("");
    }
    so.clear(); //here is the solution
}
for (int i = 0; i < userVector.size(); i++)
    cout << userVector[i] << endl;