解析基于逗号的文本文件时出现问题 (C++)

Trouble with parsing text file based on commas (C++)

本文关键字:问题 C++ 文件 于逗号 文本      更新时间:2023-10-16

我正在努力创建一个程序,该程序应该逐行读取文本文件(例如狗,伙伴,,125,,,猫,,,等...)并根据逗号解析它。这就是我到目前为止所拥有的,但是当我运行它时,什么也没发生。我不完全确定我做错了什么,我对更高层次的概念相当陌生。

#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
#include <cstdlib>
#include <sstream>
#include <vector>
using namespace std;
int main()
{
std::ifstream file_("file.txt"); //open file 
std::string line_; //declare line_ as a string
std::stringstream ss(line_); //using line as stringstream
vector<string> result; //declaring vector result
while (file_.is_open() && ss.good())
{ //while the file is open and stringstream is good
std::string substr; //declares substr as a string
getline( ss, substr, ',' ); //getting the stringstream line_ and substr and parsing
result.push_back(substr);
}
return 0;
}

您是否忘记添加像std::getline(file_, line_);这样的行?file_根本没有被读取,line_在宣布为空时立即放入ss

我不确定您为什么检查file_在您的循环条件下是否打开,因为除非您关闭它,否则它将始终处于打开状态。

据我所知,使用good()作为循环条件不是一个好主意。只有在第一次尝试读取文件末尾时才会设置标志(如果在点击分隔符时准确地读取到文件的末尾,则不会设置标志),因此如果文件末尾有一个逗号,循环将额外运行一次。相反,您应该以某种方式在提取之后和使用提取结果之前放置标志检查。一种简单的方法是仅使用getline()调用作为循环条件,因为该函数返回流本身,当转换为布尔值时,流等效于!ss.fail()。这样,如果在没有提取任何字符的情况下到达文件的末尾,则循环将不会执行。

顺便说一下,像//declaring vector result这样的注释几乎毫无用处,因为它没有提供您无法从代码中轻松看到的有用信息。

我的代码:

#include <iostream>
#include <fstream>
#include <vector>
#include <sstream>
int main()
{
std::ifstream file("input.txt");
std::string line, word;
std::vector<std::vector<string>> result; //result[i][j] = the jth word in the input of the ith line
while(std::getline(file, line))
{
std::stringstream ss(line);
result.emplace_back();
while(std::getline(ss, word, ','))
{
result.back().push_back(word);
}
}
//printing results
for(auto &i : result)
{
for(auto &j : i)
{
std::cout << j << ' ';
}
std::cout << 'n';
}
}