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

时间:2014-01-28 19:49:47

标签: c++ string file-io format

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

  

输入文件|数据读取

     

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 ++中执行此操作吗?

谢谢!

3 个答案:

答案 0 :(得分:1)

“有人可以给我一个提示如何在C ++中执行此操作吗?”

当然可以:

  1. 使用std::getline逐行浏览您的文件,将每行读入std::string line;
  2. 为每一行构建一个临时std::istringstream对象
  3. 在此流上使用>>运算符来填充double类型的变量(第1列)
  4. 再次使用>>将第2列读入您不会实际使用的std::string
  5. 使用>>阅读另一个double(第3列)
  6. 即。类似的东西:

    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;
        }
    }
    

答案 1 :(得分:0)

  

有人可以给我一个提示如何在C ++中执行此操作吗?

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

解决问题的最佳方法应该是使用std::ifstream逐行阅读(请参阅std::string::getline()),然后使用{{1}分别解析(并跳过上面提到的列)每一行在输入文件中所有行的循环中。

答案 2 :(得分:0)

问题解决如下:

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;
}

感谢所有人!!