简体   繁体   中英

Reading ints from .txt file to vector?

For some reason I am getting zero values in my vector when I try to read from a txt file.

Here is my code:

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

}

The txt file is rather long but the format is: 37107287533902102798797998220837590246510135740250 46376937677490009712648124896970078050417018260538 74324986199524741059474233309513058123726617309629 91942213363574161572522430563301811072406154908250 23067588207539346171171980310421047513778063246676

Here is reading one by one:

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

}

But i recommend you reading line by line or if the file is no so big reading all in an std::string and process the string (reading from file is expensive).

In order to store each digit as an int, read each line and store it in a string. Then process each line.

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM