c++ - 遍历字符串时尝试访问子字符串的编译器错误

标签 c++ string stl iterator

我试图找到一种方法来解析存储在 string 对象中的文本文件,但没有成功。字符串格式如下:

...
1  45
1  46
1  47
2  43
2  44
2  45
...

我正在尝试遍历整个字符串,抓取每一行,然后将字符串拆分为第一个整数和第二个整数以进行进一步处理。但是,这样做是行不通的:

string  fileContents;

string::iterator index;

for(index = fileContents.begin(); index != fileContents.end(); ++index)
{
   cout << (*index);       // this works as expected

   // grab a substring representing one line of the file
   string temp = (*index); // error: trying to assign const char to const char*
}

我正在尝试找到一种方法来做到这一点,但到目前为止我还没有找到任何运气。

最佳答案

使用istringstream s 和 std::getline()从每一行获取整数:

#include <iostream>
#include <sstream>
#include <string>

int main()
{
    std::istringstream in("1 45\n1 47\n");
    std::string line;
    while (std::getline(in, line))
    {
        std::istringstream nums(line);
        int i1, i2;
        if (nums >> i1 && nums >> i2)
        {
            std::cout << i1 << ", " << i2 << "\n";
        }
    }
    return 0;
}

参见 http://ideone.com/mFmynj 的演示.

关于c++ - 遍历字符串时尝试访问子字符串的编译器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13425000/

相关文章:

c++ - 这会产生内存泄漏吗?

c++ - 在 C++ 中连接两个大文件

c++ - 为什么包含任意 STL header 可以解决这些编译错误?

c++ - *&++i 会在 C++03 中导致未定义的行为吗?

c++ - 用父类(super class)的实例覆盖子类的实例

python - 将数字分解为其他数字

c++ - 如何从命令行参数 C++ 创建 std::string

c++ - 多重继承模糊函数

c++ - 使用 Qt 隐藏元素

c++ - 从展平的 3D 数组计算 3D 坐标