简体   繁体   中英

Reading into a vector from a .txt file c++

So I need to make a program that acts as a virtual dictionary. Whilst I don't want anyone to write my code for me, I'd appreciate some feedback on my code and maybe a point in the right direction to find some information on a problem im having.

Most of my program works fine, I'm having issues populating my vector from a.txt file and admittedly I dont really understand how it works.

Heres what I've been using:

    ifstream myfile(filename);
    if (myfile.is_open())
    {
        string Line;
        string buffer;
        string currentWordType = "none";
        string currentWord = "none";
        string currentWordDef = "none";
        while (!myfile.eof())

        getline(myfile, buffer);
        currentWordType = buffer;

        getline(myfile, buffer);

        currentWord = buffer;

        getline(myfile, buffer);

        currentWordDef = buffer;

        Word newWord(currentWordType, currentWord, currentWordDef);
        wordList.push_back(newWord);

    }
    myfile.close();

Again I'm not exactly looking for someone to do this for me, just maybe point out some area's ive gone wrong and point me in the right direction.

Thanks!

To read three strings from a line each you need a loop... but instead of just checking for eof

 while (.myfile.eof())

we check all the error states of the stream

while( myfile ){ ...
};

After each read we should check whether that succeded...

      std::string currentWordType;
      if( ! getline(myfile, currentWordType)) {
          break;
      }
      std::string currentWord;
      if( ! getline(myfile, currentWord)) {
          break;
      }
      std::string currentWordDef;
      if( ! getline(myfile, currentWordDef)) {
          break;
      }

Afterwards we can add the Word to wordList as before.

Word newWord(currentWordType, currentWord, currentWordDef);
wordList.push_back(newWord);

See working example here

Alternatively you can parse inside the condition

while( myfile >> currentWordType >> currentWord >> currentWordDef ) {     
    Word newWord(currentWordType, currentWord, currentWordDef);
    wordList.push_back(newWord);      
};

See working example here

there is the while loop you forgot {}, in this instance it will run only the next line which:

getline(myfile, buffer);

until it will reach eof, which means it will overwrite it each time. if you can fix the code so we know that is not the problem. also can you post what error exactly you are getting, or what is the output you are getting, it would help.

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