0

I am working on a program that should read from a file and store the contents of that file in a vector. I must read the contents of the .txt file and push the strings back into a vector before it reaches a ' '. If it is a space you will skip that part of the file and continue pushing back the contents after the space. Does anybody know what function to use to read from a file and put the contents into a vector or array? Thanks for your time.

int main()
{
    Code mess;
    ifstream inFile;
    inFile.open("message1.txt");
    if (inFile.fail()) {
        cerr << "Could not find file" << endl;
    }
    vector<string> code;
    string S;
    while (inFile.good()) {
        code.push_back(S);
    }
    cout << mess.decode(code) << endl;
return 0; 
}
Mbusi Hlatshwayo
  • 504
  • 10
  • 23
  • You will need to use fopen, fgets, fclose. Please be sure to post your code before you ask your next question. – Mike Nakis Feb 12 '15 at 23:24
  • 7
    break the problem down into parts, dont worry about storing in a vector or array, just read the file and output the strings. Hint : use cin or fgets (as Mike says) – pm100 Feb 12 '15 at 23:24
  • 1
    `while (inFile.good())` should be `while(inFile >> s)`, and that should do it. – vsoftco Feb 12 '15 at 23:36
  • Please search StackOverflow for examples of reading a file into an array: [Examples of reading into vector](https://www.google.com/search?q=stackoverflow+c%2B%2B+read+vector&ie=utf-8&oe=utf-8) – Thomas Matthews Feb 12 '15 at 23:39

2 Answers2

1

Basically you can also do it like this :

std::ifstream fh("text.txt");
    std::vector<std::string> vs;
    std::string s;
    while(fh>>s){
             vs.push_back(s);
    }

    for(int i=0; i<vs.size(); i++){

            std::cout<<vs[i]<<std::endl;
    }
0

You should change your reading code to

while (inFile >> S) {
    code.push_back(S);
}

Your current code doesn't read anything into your S variable.


Regarding loop conditions while (inFile.good()) see this Q&A please:
Why is iostream::eof inside a loop condition considered wrong?

Using std::iostream::good() has more or less the same issues.

Community
  • 1
  • 1
πάντα ῥεῖ
  • 83,259
  • 13
  • 96
  • 175
  • Thanks for your help you fixed my problem. I am just wondering what the difference between inFile >> S and inFile.good() is though. – Mbusi Hlatshwayo Feb 12 '15 at 23:50
  • @MbusiHlatshwayo `inFile.good()` just checks the state of the stream, but doesn't read anything from it, while `inFile >> S ` does. The latter statement also returns a reference to the stream, and that's checked for state because of the implicit boolean conversion provided by [`std::istream::operator bool`](http://en.cppreference.com/w/cpp/io/basic_ios/operator_bool). – πάντα ῥεῖ Feb 12 '15 at 23:55