-2

I am trying to write program that takes strings stored in a vector, and then adds them to a .txt file, and then if I want fill a vector with the strings that are saved on to the .txt file and let me print them out.

But when I tried to do it, it said that the vector had not been filled, ifstream and >> not work with loading strings into a Vector.

int main()
{
    vector<string> champ_list;
    vector<string> fri_list;
    string champ_name;
    string list_name;
    string champ_again;
    cout <<"Pleas enter in the name of the list for your Random pick\n"; 
    cin>>list_name;

    do
    {
        cout <<"Please enter in the name of the champion you would like to add to the list\n";
        cin>>champ_name;
        champ_list.push_back(champ_name);
        cout <<"Would you like to add another name to the list y/n\n";
        cin>>champ_again;
    } while(champ_again == "y");
    cout <<"1\n";

    ofstream mid_save("mid.txt");
    mid_save<<champ_list[0]<<"\n";
    cout <<"2\n";

    // This is where the program crashes 
    ifstream mid_print("mid.txt");
    mid_print>>fri_list[0];
    cout<<"3\n";

    cout <<fri_list[0];
    cin>>list_name;

    return 0;
};
2
  • If you would capitalize and punctuate conventionally, it would be appreciated. Also, if this is a homework question, please add the homework tag.
    – thb
    Jun 24, 2012 at 23:50
  • Pls search the stackoverflow website for your questions first. This looks like a duplicate of a variety of string parsing questions asked here. If you don't find answer to your perticular questions after searching then u can post ur question. Otherwise your question will be voted tone closed.
    – Jay D
    Jun 25, 2012 at 0:07

1 Answer 1

2

I suspect that you want to close the "mid.txt" file before you reopen it for reading. You should definitely test the state of your file streams to be sure they successfully open. For example:

ofstream mid_save("mid.txt");
if (!mid_save) {
    std::cerr << "can't open mid_save\n";
    return 1;
}
mid_save<<champ_list[0]<<"\n";
cout <<"2\n";
mid_save.close(); // Close the file before reopening it for input

ifstream mid_print("mid.txt");
if (!mid_print) {
    std::cerr << "can't open mid_print\n";
    return 1;
}
mid_print>>fri_list[0];
cout<<"3\n";

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.