-2

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

但是当我尝试这样做时,它说向量没有被填充,ifstream 和 >> 不适用于将字符串加载到向量中。

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;
};
4

1 回答 1

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";
于 2012-06-25T00:37:52.130 回答