从.text文件读取向量?

时间:2014-07-20 02:55:23

标签: c++

由于某种原因,当我尝试从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

2 个答案:

答案 0 :(得分:3)

以下是逐一阅读:

#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中没有那么大的读数并处理字符串(从文件中读取是昂贵的)。

答案 1 :(得分:0)

为了将每个数字存储为int,请读取每一行并将其存储在字符串中。然后处理每一行。

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.";

}