我试图找到一种方法来解析存储在 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/