0

我徒劳地试图找到一种方法来解析存储在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*
}

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

4

2 回答 2

4

使用istringstreams 和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上的演示。

于 2012-11-16T22:04:22.910 回答
0

Astd::string::iterator标识一个char。Achar可以用来形成一个元素std::string,但这可能不是你想要的。相反,您可以使用两个迭代器来创建一个std::string,例如:

for (std::string::const_iterator begin(s.begin()), it(begin), end(s.end());
     end != (it = std::find(it, end, '\n'); begin = ++it) {
    std::string line(begin, it);
    // do something with the line
}

std::string正如所指出的,将流功能与您创建的流一起使用可能会更容易。

于 2012-11-16T22:24:57.277 回答