如何在C++中从文本文件中读取时跳过特定的列

How to skip specific column while reading from text file in C++?

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

我有一个包含三列的文本文件。我只想读第一篇和第三篇。第二列由名称或日期组成。

输入文件|数据读取

7.1 2000-01-01 3.4 | 7.1 3.4

1.2 2000-01-02 2.5 | 1.2 2.5

5.5未知3.9 | 5.5 3.9

1.1未知2.4 | 1.1 2.4

有人能给我一个如何在C++中做到这一点的提示吗?

谢谢!

"有人能给我一个如何在C++中做到这一点的提示吗?">

当然:

  1. 使用std::getline逐行浏览文件,将每一行读取到std::string line;
  2. 为每行构造一个临时std::istringstream对象
  3. 在此流上使用>>运算符填充double类型的变量(第一列)
  4. 再次使用>>将第2列读取到您不会实际使用的std::string
  5. 使用>>读取另一个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++中做到这一点吗?

只需使用std::basic_istream::operator>>将跳过的数据放入伪变量,或使用std::basic_istream::ignore()跳过输入,直到指定下一个字段分隔符。

解决它的最佳方法应该是使用std::ifstream逐行读取(请参见std::string::getline()),然后分别解析(并如上所述跳过列)每一行,在输入文件中的所有行上循环使用std::istringstream

问题解决如下:

int main()
{   
ifstream file("lixo2.txt");
string line; int nl=0; int nc = 0; double temp=0;
vector<vector<double> > matrix;
while (getline(file, line))
{
size_t found = line.find("Unknown");
line.erase (found, 7);
istringstream is(line);
vector<double> myvector;
while(is >> temp)
{
myvector.push_back(temp);
nc = nc+1;
}
matrix.push_back(myvector);
nl =nl+1;
}
return 0;
}

感谢大家!!