istringstream Confusion未返回正确值

istringstream Confusion not returning correct value

本文关键字:返回 Confusion istringstream      更新时间:2023-10-16

我对这项工作感到震惊。我想做的是:

cin中读取一整行,并将其扫描为integer(使用字符串流)。如果扫描成功,则返回整数值。如果参数不是合法整数,或者字符串中出现无关字符(空白字符除外),则用户有机会重新输入值。prompt和repmpt参数都是可选的。

如果提供,则在读取值之前打印可选提示字符串。如果提示没有以空格结束,则在打印时会添加一个空格。如果提供了可选的重试字符串,则当输入不可接受时,该字符串将用作错误消息。如果未提供任何重传字符串,则使用字符串"无效整数格式。请重试:"。

原型是:

int getInt(const string& prompt,
    const string& reprompt){
    int n;
    bool pass = true;
    while (pass != false){
        string line = getLine(prompt);
        istringstream s(prompt);
        s >> n >> ws;
        for (size_t i = 0; i < line.length(); i++){
            if (i == ': '){
                return isdigit(n);
            }
            else if (i != ': '){
                i++;
                line = i + ' ';
            }

        }
        if (s.fail() || !s.eof()){
            cerr << reprompt;
            pass = false;
        }
    }
    return n;
}

结果:

 3. Make sure getInt returns values correctly
Invalid integer format. Try again:    X Calling getInt("123")->123: 
expected [123] but found [-858993460]

注释处理代码不太好,所以我把它作为一个答案来写。

您似乎想做的是编写一个函数,从某个输入流中读取一行,然后将其解析为整数,同时验证实际的整数var输入?

然后你开始好吧,但在解析/验证中你有点搞砸了。

你所要做的就是例如

std::string line = getLine(prompt);
for (;;)
{
    std::istringstream iss(line);
    int n;
    if (iss >> n)  // This does both parsing and validation
        return n;
    // If we reach here, input was not an integer
    line = getLine(reprompt);
}