c++ - C++简单文件I/O问题

标签 c++

我有这段代码可以读取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
等等...
现在,我在两件事上挣扎。
  • 由于某种原因,该代码会跳过第一个值,并两次读取最后一个值。
  • 我无法找到一种方法来一次读取所有5列并将它们自动放入单独的文本文件中。当我尝试执行此操作之前,它会跳过每一列的所有其他值。

  • 我将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/

    相关文章:

    c++ - 将头文件添加到 C++ 的 eclipse 构建路径

    c++ - 我应该使用一类函数还是函数的命名空间?

    c++ - std::is_default_constructible<T> 错误,如果构造函数是私有(private)的

    c++ - 在 C++ 中插入类型映射

    c++ - 未声明的复制构造函数是否自动内联?

    c++ - 如何在 C++ 中创建不同的对象?

    c++ - 未命名的命名空间和 iostream 导致 "!= being illegal operation"

    c++ - 从头开始实现经典 OPC DA 服务器

    c++ - 调用包含可调用对象和参数的元组

    c++ - 如何在 Arduino 上添加 time_t ?