所以我试图利用istringstream来解析一个文本文件。这个想法是按空格分解每一行,并根据子字符串做一些事情。代码运行良好,除了两件事之外,它重复计算每一行的最后一个子字符串,并且当它完成读取文件时,它会出现seg错误。我以前没有使用过sstream,所以任何见解都会有所帮助。
file.getline(str,80);
while(!file.eof())
{
cout<<str<<endl;
istringstream iss(str);
while (iss)
{
iss >> sstr;
cout << "Substring: " <<sstr << endl;
}
file.getline(str,80);
}发布于 2011-09-09 01:46:15
while循环应该是这样的:
std::string line;
while (std::getline(file, line))
{
std::istringstream iss(line);
std::string token;
while (iss >> token)
{
cout << "Substring: " << token << endl;
}
}getline和input操作返回流对象,该对象本身有一个专门的转换为bool,表示操作是否成功,当您到达相应流的末尾时,它将准确地失败。
发布于 2011-09-09 01:47:17
while !eof is almost always wrong。
切换到不同的C++书籍,并告诉我们您现在使用的是哪本书,以便我们可以相应地进行模拟和警告。
while (file.getline(str,80)) {
cout<<str<<endl;
istringstream iss(str);
while (iss >> sstr) {
cout << "Substring: " <<sstr << endl;
}
}https://stackoverflow.com/questions/7352193
复制相似问题