简体   繁体   中英

Vector, Structure and While loop - reading from a file

I have a text file with information in it. It looks like this:

Rimas 252 45
Robertas 187 13
Jurgis 205 36
Matas 58 50
Antanas 145 5
10 20

As you see every line has three different members(Name, first number, second number), until the last line, which has only two members(two numbers). I'm trying to read this information to my code. Everything works fine until the last line, because it has two members and doesn't have a string in that line. I need to make my code to recognize the different line and read it other method, not the same as the line above.


#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

struct lankytojai { // name, first number, second number
    string vardas;
    int litai;
    int ltcentai;
};

void read(vector<lankytojai> l) {
    ifstream failas("vvv.txt"); //reads three members correct, last two incorrectly
    int i = 0;
    while(failas) {

        lankytojai lan;
        int lt;
        string var;

        while(!(failas >> lan.ltcentai)) {
            failas.clear();
            if(failas >> var) {
                lan.vardas += var;
            }
            if(failas >> lt) {
                lan.litai = lt;
            }
            else {
                return;
            }
        }

        l.push_back(lan);
        cout << l[i].vardas << " " << l[i].litai << " " << l[i].ltcentai << endl;
        i++;
    }

}

int main() {
    vector<lankytojai> l;
    read(l);
    return 0;
}

Simply restructure your code to use std::getline() to get a whole line at a time (as a std::string ), then check how many spaces it contains.

for (string line; getline(failas, line); ) {
    size_t space_count = count(line.begin(), line.end(), ' ');
    // ...
}

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