c++读多列文件

C++ Read File with multiple column

本文关键字:文件 c++      更新时间:2023-10-16

我想读取一个具有多列,不同变量类型的文件。列的数量不确定,但在2或4之间。例如,我有一个文件:

  • string int
  • string int string double
  • string int string
  • string int string double

谢谢!

我把列数修改为2到5,而不是原来写的4或5。

可以先读std::getline

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

,然后用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
    }
}

如果列可能包含不同的类型,则必须首先读入字符串,然后尝试确定正确的类型。