简体   繁体   中英

Reading integers from a text file and storing them into a vector using C++

I am trying to read the last number of each line from a datafile. When I read the last two digit it converts into string. My code looks like (upto this point):

#include <iostream>
#include <vector>
#include <fstream>
using namespace std;
int main() {
  string line;
  ifstream fin;
  fin.open("prim.txt");
  while (fin) {
    getline(fin, line);
    // cout<<line<<endl;
    string s;
    int i = 0;
    for (int i = line.size() - 2; i < line.size(); i++) {
      s = s + line[i];
    }
    cout << s << endl;
  }
  fin.close();
  return 0;
}

the textfile from which I want to fetch data is: prim.txt

I want to store the last numbers of each line into a vector of int type.

If each line of the file contains 3 numbers seperated by space, there is no need for sophisticated parsing via getline . Simply read 3 numbers until reading fails and store the last of them in a vector:

 std::vector<int> numbers;
 int a,b,c;
 while( fin >> a >> b >> c) numbers.push_back(c);

Your code assumes that the last number has 2 digits, which may not always be the case. Also this fails, when there are trailing spaces in a line. Further, reading as string and then converting to int is not necessary when you can read int s directly. Last but not least, your contidion while(fin) is "too late", because the last getline will fail when there is no more line to read, but then you still try to process the line (if you wanted to stay with getline you could use while(getline(fin,line)) ).

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