我不知道这是否真的很奇怪,或者应该是这样,但这是我目前的挣扎。假设我们有这样的东西:
stringstream sso("12 1442 nana 7676");
double num = 0;
while(sso >> num || !sso.eof()) {
if(sso.fail()) {
sso.clear();
string dummy;
sso >> dummy;
continue;
}
cout << num << endl;
}其结果是:
12
1442
7676如预期的那样。但是,例如,如果我将字符串文本更改为12 + 1442 nana 7676,则得到:
12
7676为什么角色'+'在这里搞砸了呢?
发布于 2020-04-02 21:32:46
正如我们现在所知道的,+是double的一个有效令牌,所以您需要一种方法来跳过下一个空格分隔的令牌,而不是仅仅摆脱它。这个函数可以为您完成以下任务:
template<class Ct>
std::basic_istream<Ct>& next_token(std::basic_istream<Ct>& is) {
is.clear();
std::ctype<Ct> const& ctype = std::use_facet<std::ctype<Ct>>(is.getloc());
if (ctype.is(ctype.space, is.peek())) {
return is >> std::ws;
}
Ct c;
while (is.get(c) && !ctype.is(ctype.space, c)) {
;
}
return is;
}然后,您可以将代码更改为:
stringstream sso("12 + 1442 nana 7676");
double num = 0;
while (sso) {
if (!(sso >> num)) {
sso >> next_token;
} else {
cout << num << endl;
}
}输出:
12
1442
7676https://stackoverflow.com/questions/60999502
复制相似问题