从.txt文件中获取字符串到Vector中

时间:2012-06-24 23:46:49

标签: c++

我正在尝试编写将字符串存储在向量中的程序,然后将它们添加到.txt文件中,然后如果我想填充带有保存在.txt文件中的字符串的向量,让我打印出来。

但是当我尝试这样做时,它说向量没有被填充,ifstream和>>无法将字符串加载到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;
};

1 个答案:

答案 0 :(得分:2)

我怀疑你想在重新打开它之前关闭“mid.txt”文件。您绝对应该测试文件流的状态以确保它们成功打开。例如:

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";