0
votes

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; 
}
2
You will need to use fopen, fgets, fclose. Please be sure to post your code before you ask your next question. - Mike Nakis
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
while (inFile.good()) should be while(inFile >> s), and that should do it. - vsoftco
Please search StackOverflow for examples of reading a file into an array: Examples of reading into vector - Thomas Matthews

2 Answers

1
votes

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
votes

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.