我有这段代码可以读取CSV格式的txt文件(实际文件长为数百万行):
1,2,3,4,5,
6,7,8,9,10,
11,12,13,14,15,
16,17,18,19,20,
etc...
该代码的目的是将导入的文本文件的每一列分隔为一个单独的文件。例如,使用上述示例数据,文本文件1将为1
6
11
16
文本文件2为2
7
12
17
等等...现在,我在两件事上挣扎。
我将while循环中的每个“out_file”语句都注释掉了,这样我就可以手动进行一个接一个的操作,这样可以解决跳过其他所有值的问题,但是当一个一列地处理时,仍然存在第一个和最后一个值问题。
这是我的代码:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main(int argc, char *argv[]) {
string line1;
string value1;
string value2;
string value3;
string value4;
string value5;
ifstream in_file ("in_file_comma_appended.txt");
ofstream out_file;
out_file.open("out_file.txt");
if (in_file.is_open())
{
while (getline(in_file,line1))
{
getline(in_file, value1, ',');
out_file << value1 << "\n";
getline(in_file, value2, ',');
//out_file << value2 << "\n";
getline(in_file, value3, ',');
//out_file << value3 << "\n";
getline(in_file, value4, ',');
//out_file << value4 << "\n";
getline(in_file, value5, ',');
//out_file << value5 << "\n";
}
in_file.close();
out_file.close();
}
return 0;
}
请让我知道如何解决这些问题。
最佳答案
您的循环正在从文件中读取整行,但是对该行不执行任何操作,只是将其丢弃。在循环内部,然后从输入文件中读取接下来的5个单独的值,并将它们写入输出文件。但是在下一个循环迭代中,您将再次读取下一行,并将其丢弃。等等。这就是为什么您跳过值。
在循环内部,使用std::istringstream
从循环条件已读取的行字符串中读取值,例如:
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
using namespace std;
int main(int argc, char *argv[])
{
ifstream in_file ("in_file_comma_appended.txt");
if (in_file.is_open())
{
ofstream out_files[5];
for (int i = 0; i < 5; ++i) {
out_files[i].open ("out_file_" + to_string(i+1) + ".txt");
}
string line, value;
while (getline(in_file, line))
{
istringstream iss(line);
for(int i = 0; i < 5; ++i)
{
getline(iss, value, ',');
out_files[i] << value << "\n";
}
}
}
return 0;
}
关于c++ - C++简单文件I/O问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64867479/