gpt4 book ai didi

c++ - 在 C++ 中使用 istringstream 将字符串拆分为整数

转载 作者:IT老高 更新时间:2023-10-28 22:24:49 27 4
gpt4 key购买 nike

我正在尝试使用 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com