我想读一个包含多列,不同变量类型的文件.列数不确定,但在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)) {
...
}
Run Code Online (Sandbox Code Playgroud)
然后使用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
}
}
Run Code Online (Sandbox Code Playgroud)
如果列可能包含不同类型,则必须首先读入字符串,然后尝试确定正确的类型.
| 归档时间: |
|
| 查看次数: |
11910 次 |
| 最近记录: |