[英]How to read entire stream of integers from fgets and push back into 1D vector?
您好,我正在使用c ++,並且我使用fgets讀取了文件,我正在使用while循環和sscanf將其推回到我的矢量兩倍,而我想使用一行來完成它,例如ifstream但我不想使用排隊。
%% 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>{}};
(改編自此答案 )。
這里有一些指針可以幫助您:
因此您的代碼可能如下所示:
#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;
}
這樣做的方法甚至更簡潔,但是我建議像在代碼中一樣處理separatley的每一行。 也許您的文件包含其他行,並且您希望以不同的方式進行處理。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.