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

标签 c++ stl istringstream

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

相关文章:

c++ - LLVM IO 错误 - 写入 bc 文件时出错

c++ - 检查 uint8_t[8] 是否包含任何非 0 并使用一次内存负载访问非零插槽

c++ - 为什么 C++ STL 函数调用需要如此冗长?

c++ - 编写此代码的正确方法是什么?

c++ - 无法理解 C++ 中的 istringstream

C++ - 重复使用 istringstream

c++ - 为什么 WinAPI 不创建具有配置大小的窗口?

c++ - 在 ‘n’ 行中打印 Zig-Zag 字符串的串联

c++ - 如何初始化静态 std::map?

c++ - 将文本文件存储到类中