dimanche 21 juin 2020

How to skip the space and the new line from stringstream and put them in a vector?

I'm trying to read a text file that contains information of a person (name, age, occupation) as follows:

name 20
occupation
name 25
occupation
name 34
occupation

I read the whole file and for each line I used istringstream to skip the space between the name and the age.

std::vector<string> readfile(std::vector<std::string> *words, char *argv){

    std::ifstream file(argv);   //Opens the file specified on execution

    if ( !file ){
        cerr << "Le fichier " << argv << " n'existe pas" << endl;
        exit (-1);
    } else {
            std::string line;
            while (std::getline(file, line)){
                        istringstream ss(line);
                        do {
                                string word;
                                ss >> word;
                                if (word != " " || word != "\n"){
                                        words->push_back(word);
                                };
                        } while (ss);
                };
                file.close();
        };
        return *words;
};

My main is:

int main( int argc, char *argv[] ){
        std::vector<std::string> compV;

        readfile(&compV,argv[1]);
        cout << compV.at(2) << endl;
        
        return 0
}

When I compile and execute the program, I get a space as the result. compV.at(0) shows name comV.at(1) shows age but comV.at(2) shows a space instead of occupation.

What did I do wrong here ?

Aucun commentaire:

Enregistrer un commentaire