【问题标题】:How to skip specific column while reading from text file in C++?从 C++ 中读取文本文件时如何跳过特定列?
【发布时间】:2014-01-28 19:49:46
【问题描述】:

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

输入文件                    |数据读取

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++ 中做到这一点?

谢谢!

【问题讨论】:

  • LihO,感谢您的帮助。但是,当我有一个包含几列的文件时,我该如何阅读它们。但总是跳第二栏。

标签: c++ string file-io format


【解决方案1】:

“谁能给我一个提示如何在 C++ 中做到这一点?”

确定:

  1. 使用std::getline逐行浏览文件,将每一行读入std::string line;
  2. 为每一行构造一个临时的std::istringstream 对象
  3. 在此流上使用>> 运算符填充double 类型的变量(第一列)
  4. 再次使用>> 将第二列读入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;
    }
}

【讨论】:

    【解决方案2】:

    谁能给我一个提示如何在 C++ 中做到这一点?

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

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

    【讨论】:

      【解决方案3】:

      问题解决如下:

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

      谢谢大家!!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-13
        • 2018-08-20
        • 1970-01-01
        相关资源
        最近更新 更多