在 C++ 中使用 for 循环逐个字符串读取文件行中的字符串

Reading string by string in a file's lines using a for loop in C++

提问人:fslack 提问时间:11/4/2020 最后编辑:AStopherfslack 更新时间:11/4/2020 访问量:63

问:

我需要有关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 循环 while-loop ifstream istringstream

评论

1赞 Some programmer dude 11/4/2020
实际上,您根本不需要内部循环:tmp_table = std::vector<double>(std::istream_iterator<double>(iss), std::istream_iterator<double>());
0赞 Werner Henze 11/4/2020
为什么要用循环代替循环?有什么问题?顺便说一句,无需先读入,您可以直接从文件中读入双打。whileforwhilegetlinestringtoken
0赞 Some programmer dude 11/4/2020
要修改我的第一条评论,您可能应该改用:inserttmp_table.insert(end(tmp_table), std::istream_iterator<double>(iss), std::istream_iterator<double>());
0赞 fslack 11/4/2020
好的,谢谢。我把代码简化了很多,我不需要只是将 elemets 附加到tmp_table向量中,我还需要输入一些条件,所以我认为我需要内部循环。我向您展示如何修改线程。
1赞 Some programmer dude 11/4/2020
现在,拥有该循环更有意义。如果第一个循环是你想要的,你基本上可以复制它:forfor (std::string token; iss >> token; )

答: 暂无答案