【问题标题】:(C++) How to read two columns of data from .txt file into two vectors?(C++) 如何将 .txt 文件中的两列数据读入两个向量?
【发布时间】:2021-04-09 22:41:47
【问题描述】:

我一直在尝试从包含两列浮点数据的文本文件中读取数据

1 2
3 4
4.5 6.5
2 4

现在,我尝试了stackoverflow中几个问题的方法,如thisthis等。我写的最终代码是:

#include<iostream>
#include<fstream>
#include<string>
#include<vector>

using namespace std;


int main()
{
    vector<float> a, b;

    fstream file;
    file.open("sample.txt", ios::in);
    if(!file){
        cout << "Error" <<endl;
        return 0;
    }
    
    int number_of_lines = 0;
    string line;

    while(getline(file,line))
    {   
        file >> a[number_of_lines];
        file >> b[number_of_lines];
    }

    cout << number_of_lines << endl;

    for (int i = 0; i < number_of_lines; i++) //code to print out the vectors
    {
        cout << a[i] << " " << b[i] <<endl;
    }

    return 0;
}

但它似乎不起作用。如何读取向量中的数据?

【问题讨论】:

    标签: c++ vector text-files


    【解决方案1】:

    (更新):您只需要:

    float ai, bi;
    while (file >> ai >> bi) {
      a.push_back(ai);
      b.push_back(bi);
      number_of_lines++;
    }
    

    【讨论】:

      【解决方案2】:

      使用错误检查添加我的变体(您需要替换异常类型)。从这里使用修剪:What's the best way to trim std::string?

      // trim from start (in place)
      static void ltrim(std::string &s) {
          s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](unsigned char ch) {
              return !std::isspace(ch);
          }));
      }
      
      
      // trim from end (in place)
      static void rtrim(std::string &s) {
          s.erase(std::find_if(s.rbegin(), s.rend(), [](unsigned char ch) {
              return !std::isspace(ch);
          }).base(), s.end());
      }
      
      
      // trim from both ends (in place)
      static void trim(std::string &s) {
          ltrim(s);
          rtrim(s);
      }
      
      
      std::vector<std::vector<double>> load_dat_file(const std::string& file_name) {
        std::vector<std::vector<double>> res;
      
        ifstream fin;
        fin.open(file_name, ios::in);
      
        int linenr = 1;
        string line;
        while(getline(fin, line)) {
          // is only whitespace? -> skip
          trim(line);
          if (line == "") {
            continue;
          }
      
          size_t pos = line.find_first_of(" \t");
          if (pos == string::npos) {
            throw RuntimeError("Invalid format of input file " + file_name +
                ", did not find a column separator on line " + to_string(linenr) + ".");
          }
      
          string col1 = line.substr(0, pos);
          string col2 = line.substr(pos + 1);
      
          char* end;
          errno = 0;
          double col1_value = strtod(col1.c_str(), &end);
          if (errno != 0 || *end != '\0') {
            throw RuntimeError("Invalid format of input file " + file_name +
                ", could not convert value in the first column " + col1 + " to a float, error on line " + to_string(linenr) + ".");
          }
      
          errno = 0;
          double col2_value = strtod(col2.c_str(), &end);
          if (errno != 0 || *end != '\0') {
            throw RuntimeError("Invalid format of input file " + file_name +
                ", could not convert value in the second column " + col2 + " to a float, error on line " + to_string(linenr) + ".");
          }
      
          res.push_back(std::vector<double>());
          res.back().push_back(col1_value);
          res.back().push_back(col2_value);
      
          linenr++;
        }
      
        return res;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-09
        • 1970-01-01
        • 1970-01-01
        • 2021-05-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多