如何从 fgets 读取整个整数流并推回一维向量?

How to read entire stream of integers from fgets and push back into 1D vector?

你好,我正在使用 C++,我使用 fgets 读取文件,我正在使用 while 循环和 sscanf 推回到我的 vector double 而我想使用单行来完成它,就像在 ifstream 的情况下但是我不想使用 get line。

%% My stream of data
  151  150  149  148  147  146  145  144  143  143  141  139  138  137  135 
  132  130  130  129  128  127  127  128  129  130  129  128  127  126  127 
  127  127  127  128  128  128  129  130  130  131  131  132  132  133  133 

%% My code
vector<double> vec_TEC1D;
double temp_holder = 0.0;

while(!feof(fileptr))
    {
      fgets(line, LENGTH_LINE, fileptr);
      .....
      while(strstr(line, '\n') != NULL){
                  sscanf(line, "%lf", &temp_holder);
                  vec_TEC1D.push_back(temp_holder);
              }
      }     

我已经在上述循环之外使用 2 个 while 循环用于其他目的,因此我想避免这种情况..

感谢您的帮助!! :) 普里亚

为什么不使用 std::ifstream

std::ifstream fin(filename);
std::vector<double> vec_TEC1D{ std::istream_iterator<double>{fin},
                               std::istream_iterator<double>{}};

(改编自this answer)。

以下是一些可能对您有所帮助的建议:

因此您的代码可能如下所示:

#include <algorithm>
#include <fstream>
#include <iostream>
#include <iterator>
#include <sstream>
#include <string>
#include <vector>


int main(int argc, char* argv[]) {
  if(argc < 2)
    return -1;

  std::ifstream input(argv[1]);
  std::vector<double> data;
  std::string line;
  while(std::getline(input, line)) {
    std::stringstream converter(line);
    std::copy(std::istream_iterator<double>(converter),
          std::istream_iterator<double>(),
          std::back_inserter(data));
  }

  // Do something with the data, like print it...
  std::copy(begin(data), end(data), std::ostream_iterator<double>(std::cout, " "));
  return 0;
}

还有更简洁的方法可以做到这一点,但我建议像您在代码中那样分别处理每一行。也许您的文件包含其他行,您希望以不同方式处理这些行。