istringstream Confusion未返回正确值
istringstream Confusion not returning correct value
我对这项工作感到震惊。我想做的是:
从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);
}
相关文章:
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- 什么时候在C++中返回常量引用是个好主意
- 你能重载对象变量名本身返回的内容吗
- 为什么 Serial.println(<char[]>);返回随机字符?
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 如何获取std::result_of函数的返回类型
- QueryWorkingSet总是返回false
- (C++)分析树以计算返回错误值的简单算术表达式
- 访问者访问变体并返回不同类型时出错
- 如何返回一个类的两个对象相加的结果
- OpenInventor从9.8升级到10.4.2后,GLSL纹理返回零
- lower_bound()返回最后一个元素
- "throw expression code" 1e7 >返回 d 是什么?投掷标准::overflow_error( "too big" ) : d;意味 着?
- 奇怪的(对我来说)返回声明 - 在谷歌上找不到任何关于它的信息
- 如何取消对nullptr的屏蔽,返回正确的对象
- 奇怪的结构&GCC&clang(void*返回类型)
- 架构决策:返回std::future还是提供回调
- 从python中调用C++函数并获取返回值
- 矩阵向量乘法(cublasDgemv)返回零
- istringstream Confusion未返回正确值