C++ Read File with multiple column

后端 未结 1 2028
甜味超标
甜味超标 2020-12-19 17:26

I\'d like to read a file with multiple columns, different variable types. The number of columns is uncertain, but between 2 or four. So for instance, I have a file with :

相关标签:
1条回答
  • 2020-12-19 17:49

    You can first read the line with std::getline

    std::ifstream f("file.txt");
    std::string line;
    while (std::getline(f, line)) {
    ...
    }
    

    and then parse this line with a stringstream

    std::string col1, col3;
    int col2;
    double col4;
    std::istringstream ss(line);
    ss >> col1 >> col2;
    if (ss >> col3) {
        // process column 3
        if (ss >> col4) {
            // process column 4
        }
    }
    

    If the columns might contain different types, you must first read into a string and then try to determine the proper type.

    0 讨论(0)
提交回复
热议问题