解析基于逗号的文本文件时出现问题 (C++)
Trouble with parsing text file based on commas (C++)
我正在努力创建一个程序,该程序应该逐行读取文本文件(例如狗,伙伴,,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';
}
}
相关文章:
- 警告处理为错误这里有什么问题
- 最小硬币更换问题(自上而下方法)
- 为"adjacent"变量赋值时出现问题
- 我的神经网络不起作用 [XOR 问题]
- 在Ubuntu 16.04上安装Cilk时出现问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 编译包含字符串的代码时遇到问题
- Project Euler问题4的错误解决方案
- 问题:什么是QAbstractItemView::NoEditTriggers的反面
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 静态数据成员的问题-修复链接错误会导致编译器错误
- C++ 雷神库 - 使用资源加载器类时出现问题(不命名类型)
- 一个关于在C++中重载布尔运算符的问题
- 首要问题的答案让值班员搞错了
- setlocale的C++土耳其字符串问题
- 如何重构类层次结构以避免菱形问题
- 基于boost的程序的静态链接——zlib问题
- C++格式化输出问题
- 使用mongocxx驱动程序时包含头文件问题