提问人:fslack 提问时间:11/4/2020 最后编辑:AStopherfslack 更新时间:11/4/2020 访问量:63
在 C++ 中使用 for 循环逐个字符串读取文件行中的字符串
Reading string by string in a file's lines using a for loop in C++
问:
我需要有关C++代码的帮助,该代码从ASCII文件中读取数据并将其存储到.数据是连续存储的(如下例所示)。出于某些原因,我想用循环替换 ,就像我在第一个循环中所做的那样,当我使用 .std::vector<double>
while(iss>>token)
for
while
getline()
下面是 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
答: 暂无答案
评论
tmp_table = std::vector<double>(std::istream_iterator<double>(iss), std::istream_iterator<double>());
while
for
while
getline
string
token
insert
tmp_table.insert(end(tmp_table), std::istream_iterator<double>(iss), std::istream_iterator<double>());
for
for (std::string token; iss >> token; )