如何处理csv文件输入流,我需要将文件的每一行中的数据划分为6个不同的变量(类型字符串和int)
How to deal with csv file input stream where I need to divide the data in each row of the file into 6 different varaibles (types string and int)
我有一个数据用逗号分隔的CSV文件。文件看起来像这样:
1998,MALE,United States,45,566
1993,FEMALE,......
我将有一个类ROW的向量,数据文件中的每一行都将存储在那里。我的ROW有5个变量,我需要将它们分开,这样我就可以使用设置函数到row.set(year,sex, country, score, result)
。
知道如何读取数据吗?
从我被告知我应该尽量避免getline
。我不想将string
s转换为int
s。
任何想法?
我可能会从一个小操作符开始,以验证字符串是否存在(否则会忽略),就像这样:
std::istream &operator>>(std::istream &is, char const *pat) {
char ch;
while (isspace(static_cast<unsigned char>(is.peek())))
is.get(ch);
while (*pat && is && *pat == is.peek() && is.get(ch)) {
++pat;
}
// if we didn't reach the end of the pattern, matching failed (mismatch, premature EOF, etc.)
if (*pat) {
is.setstate(std::ios::failbit);
}
return is;
}
我们可以使用它来验证需要逗号的地方是否存在,但忽略它们则相当轻松。然后,我为ROW
类型重载operator>>
以适当地读取数据:
class ROW {
int year;
enum { MALE, FEMALE} sex;
std::string country;
int foo;
int bar;
friend std::istream &operator>>(std::istream &is, ROW &r) {
is >> r.year >> ",";
std::string s;
is >> s >> ",";
if (s == "MALE")
r.sex = MALE;
else if (s == "FEMALE")
r.sex = FEMALE;
else
error("bad sex");
std::getline(is, r.country, ',');
return is >> r.foo >> "," >> r.bar;
}
};
从这里,我们可以相当直接地创建一个向量:
// Open the file
std::ifstream in("data.txt");
// Read all the data
std::vector<ROW> rows { std::istream_iterator<ROW>(in), {}};
相关文章:
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 多个文件的内存分配错误"在抛出 'std :: bad_alloc' what (): std :: bad_alloc 的实例后终止调用" [C++]
- 两个文件使用彼此的功能-如何解决
- 停止cmake target_link_libraries将插件中静态库的两个对象文件链接到静态库本身
- 如何在C++中从文件中读取/写入多个对象
- 如何将c++编译为多个文件
- 从文件中读取多个字节,并将它们存储在C++中进行比较
- 在C++中一次将矢量值写入多个文件
- 我有两个类需要在同一 cpp 文件中相互引用,但第一个类无法识别第二个类类型的对象
- 如何传递多个 std::文件系统选项?
- 有没有办法简单地从 GPU 调用多个 cpp 输出文件?
- 如何将 2 个类分成单独的 .h 文件并正确设置它们
- 如何从txt文件中读取多个不同长度的数组?
- 结构包含在两个头文件中,这两个文件我都不拥有
- Eclipse CDT:单个项目中有多个C++文件
- clang 的 libFuzzer 可以在同一二进制文件中测试超过 1 个 API 吗?
- Levenshtein 两个文件的距离花费了太多时间
- 如何从文件中读取两个字符串和数字数组,并将它们存储在对象向量中
- C++单个生成文件多个二进制文件
- 使用 boost::p rogram_options 来解析文本文件是个好主意吗?