[英]Reading ints from .txt file to vector?
由于某种原因,当我尝试从txt文件读取时,向量中的值为零。
这是我的代码:
int main(){
ifstream read("problem13.txt");
vector<int> source;
int n;
while (read >> n){
source.push_back(n);
}
for (int i = 0; i < source.size(); i++)
cout << source[i];
cout << "Finished.";
}
txt文件相当长,但是格式为: 37107287533902102798797998220837590246510135740250
46376937677490009712648124896970078050417018260538
74324986199524741059474233309513058123726617309629
91942213363574161572522430563301811072406154908250
23067588207539346171171980310421047513778063246676
这是一本阅读的书:
#include <fstream>
#include <iostream>
#include <vector>
using namespace std;
int main(){
ifstream read("e:\\problem13.txt");
vector<int> source;
char n;
while (read >> n){
source.push_back(n - '0');
}
for (int i = 0; i < source.size(); i++)
cout << source[i];
cout << endl << "Size: " << source.size() << endl << "Finished.";
}
但是我建议您逐行阅读,或者如果文件不是很大,则全部读入std :: string并处理字符串(从文件中读取是昂贵的)。
为了将每个数字存储为整数,请读取每一行并将其存储在字符串中。 然后处理每一行。
int main(){
ifstream read("problem13.txt");
vector<int> source;
int n;
string line;
while (read >> line){
string::iterator iter = line.begin();
string::iterator end = line.end();
for ( ; iter != end; ++iter )
{
n = (*iter) - '0';
source.push_back(n);
}
}
for (int i = 0; i < source.size(); i++)
cout << source[i];
cout << "Finished.";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.