gpt4 book ai didi

C++:从控制台保存信息,然后重新打开时,信息仍然存在

转载 作者:行者123 更新时间:2023-11-28 02:52:26 25 4
gpt4 key购买 nike

我有一个程序可以将您最喜欢的游戏保存到列表中。我将如何做到这一点,以便在我关闭控制台并重新打开它时,列表仍然存在,并且数组中的所有元素都被保存?

using namespace std;

int main()
{
vector<string> games;
vector<string>::iterator iter;

while(true)
{
system("cls");
string response;
cout << "\tFavorite Videos Games \n\n";
cout << "Type 'add' to add a game.\n";
cout << "Type 'remove' to remove a game.\n";
cout << "Type 'list' to list all games.\n\n";
cout << "Type 'quit' to close and save the program.";
cout << "What would you like to do: ";
cin >> response;
cout << endl;

if ((response == "add") || (response == "remove") || (response == "list"))
{
int number;
string gameName;
if(response == "add")
{
cout << "What is the name of the game you would like to add?\n";
cout << "Name: ";
cin >> gameName;
games.push_back(gameName);
cout << gameName << " was added to the system.\n\n";
Sleep(2000);
continue;
}
if(response == "remove")
{
vector<string>::iterator linesIn;
int spacesIn;
cout << "What game should be deleted?\n\n";
cout << "All Games:\n-----------\n";
for(iter = games.begin(); iter != games.end(); ++iter)
{
number ++;
cout << number << ". " << *iter << endl;
}
cout << "Number: ";
cin >> spacesIn;
spacesIn = spacesIn -1;
linesIn = games.begin() + spacesIn;
cout << *linesIn << " was deleted.";
games.erase(linesIn);
Sleep(2000);

}
if(response == "list")
{
cout << "All Games:\n-----------\n";
for(iter = games.begin(); iter != games.end(); ++iter)
{
number ++;
cout << number << ". " << *iter << endl;
}
cout << "\n\nPress any key to continue...";
getch();
}

}
else if (response == "quit")
break;
else
{
cout << "\nInvalid action.\n\n";
Sleep(2000);
continue;
}

}
return 0;
}

最佳答案

最简单的方法是将其保存到文件中。

示例来自 http://www.cplusplus.com/doc/tutorial/files/ :

#include <iostream>
#include <fstream>
using namespace std;

int main () {
ofstream myfile;
myfile.open ("example.txt");
myfile << "Writing this to a file.\n";
myfile.close();
return 0;
}

也许添加另一个名为保存的选项,然后遍历游戏并将它们添加到名为“mygames.txt”的文件中。

然后添加一个名为“加载保存的游戏”的选项并执行如下操作:

string line;
ifstream myfile ("example.txt");
if (myfile.is_open()){
while ( getline (myfile,line) ){
games.push_back(line);
}
myfile.close();

显然,这些只是示例,但我觉得很清楚,您可以从这里获取它。

关于C++:从控制台保存信息,然后重新打开时,信息仍然存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22737718/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com