首页 > 解决方案 > 使用 C++ 中的 for 循环逐个字符串读取文件行中的字符串

问题描述

我的 C++ 代码需要帮助,该代码从 ASCII 文件中读取数据并将它们存储到std::vector<double>. 数据是连续存储的(如下例所示)。由于某些原因,当我while(iss>>token)使用.forwhilegetline()

这是代码,下面是 ASCII 文件示例。

#include <string>
#include <sstream>
#include <fstream>
#include <vector>
#include <stdio.h>     
#include <stdlib.h>

using namespace std;

int main(int argc, char** argv){

 std::ifstream file("example_file_ASCII");
 std::vector<double> tmp_table;
 std::string line;
 
 //while(std::getline(file, line)){
 for( string line; getline( file, line ); ){
   std::istringstream iss(line);
   std::string token;

   while ((iss >> token)){
     if (some conditions)
       tmp_table.push_back(std::stod(token));
     else (other conditions)
       //jump some lines for example
     }
  }
  

}

example_file_ASCII:_

1221  91.  94.  96.  98.  100.  102.  104.  106.  108.  110.  114.  118.  121.
 125.  127.  128.  131.  132.  134.  137.  140.  143.  147.  151.  155.  159.
 162.  166.  170.  173.  177.  180.  182.  186.  191.  194.  198.  202.  205.
 //the file continues

标签: c++for-loopwhile-loopifstreamistringstream

解决方案


推荐阅读