提问人:user3882729 提问时间:7/2/2023 更新时间:7/2/2023 访问量:41
带有 char 与 string 的 stringstream good() 返回值
stringstream good() return value with char vs. string
问:
我想了解为什么当下面是 vs 时行为会有所不同,特别是为什么在一种情况下返回而在另一种情况下返回。ss.good()
z
std::string
char
good()
true
false
#include <iostream>
#include <sstream>
int main() {
std::string line;
while (getline(std::cin, line)) {
std::cout << "Reading new line Size " << line.size() << "\n";
std::stringstream ss{line};
std::string z; // switch later to char
ss >> z;
if (ss.good()) {
std::cout << "Stream good\n";
} else {
std::cout << "Not good\n";
}
}
}
使用 ,程序输出为std::string z
$ ./a.out
A
Reading new line Size 1
Not good
使用 ,程序输出为char z
$ ./a.out
A
Reading new line Size 1
Stream good
答:
2赞
BoP
7/2/2023
#1
如果您检查其他状态函数,我敢肯定区别在于 .ss.eof()
读取 only 尝试读取一个字符,并且不会注意到流中是否有更多内容。char
评论
0赞
user3882729
7/2/2023
事实上,这与 EOF 是用字符串而不是 char 设置的有关。
评论