我有一个包含三列的文本文件。我只想读第一和第三。第二列由姓名或日期组成。
Input file | Data read
7.1 2000-01-01 3.4 | 7.1 3.4
1.2 2000-01-02 2.5 | 1.2 2.5
或
5.5 Unknown 3.9 | 5.5 3.9
1.1 Unknown 2.4 | 1.1 2.4
有人可以提示我如何在 C++ 中执行此操作吗?
谢谢!
最佳答案
“有人可以提示我如何在 C++ 中执行此操作吗?”
当然了:
- 使用
std::getline
逐行检查文件,将每一行读入std::string line;
- 为每一行构造一个临时的
std::istringstream
对象 - 在此流上使用
>>>
运算符来填充double
类型的变量(第 1 列) - 再次使用
>>>
将第二列读入您实际上不会使用的std::string
- 使用
>>>
读取另一个double
(第3列)
即像这样的东西:
std::ifstream file;
...
std::string line;
while (std::getline(file, line)) {
if (line.empty()) continue; // skips empty lines
std::istringstream is(line); // construct temporary istringstream
double col1, col3;
std::string col2;
if (is >> col1 >> col2 >> col3) {
std::cout << "column 1: " << col1 << " column 3: " << col3 << std::endl;
}
else {
std::cout << "This line didn't meet the expected format." << std::endl;
}
}
关于c++ - 在 C++ 中读取文本文件时如何跳过特定列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21415394/