作者热门文章
- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
我正在尝试使用 istringstream
将一个简单的字符串拆分为一系列整数:
#include <string>
#include <iostream>
#include <sstream>
#include <vector>
using namespace std;
int main(){
string s = "1 2 3";
istringstream iss(s);
while (iss)
{
int n;
iss >> n;
cout << "* " << n << endl;
}
}
我得到:
* 1
* 2
* 3
* 3
为什么最后一个元素总是出现两次?如何解决?
最佳答案
它出现了两次,因为您的循环错误,正如 http://www.parashift.com/c++-faq-lite/input-output.html#faq-15.5 中(间接)解释的那样(在这种情况下,while (iss)
与 while (iss.eof())
没有什么不同。
具体来说,在第三次循环迭代中,iss >> n
成功并获得您的 3
,并使流处于良好状态。由于这个良好的状态,循环随后运行第四次,直到下一个(第四次)iss >> n
随后失败,循环条件才被打破。但在第四次迭代结束之前,您仍然输出 n
... 第四次。
试试:
#include <string>
#include <iostream>
#include <sstream>
#include <vector>
using namespace std;
int main()
{
string s = "1 2 3";
istringstream iss(s);
int n;
while (iss >> n) {
cout << "* " << n << endl;
}
}
关于c++ - 在 C++ 中使用 istringstream 将字符串拆分为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5168670/
我是一名优秀的程序员,十分优秀!