如何使用输入编辑矢量

How do you edit a vector using input?

本文关键字:编辑 输入 何使用      更新时间:2023-10-16

我正在创建一个视频游戏商店数据库,在矢量内部编辑函数时遇到问题。例如,如果我在向量中有马里奥卡丁车,并说它拼写错误或价格变化等,我希望能够进去编辑它。我对c++还很陌生,所以如果需要的话,请批评我。

以下是我到目前为止所拥有的,顺便说一句,我正在从一个文件中提取数据并写回它

如果你想试试,这是我的完整代码http://pastebin.com/Jp0qGXZB

ifstream fin;
ofstream fout;
char resp;
string gedit;
string name;
string new_name;
const string SPACES = "                            ";
fin.open("thegamestore.txt");
fout.open("thegamestore.txt", ofstream::out | ofstream::app);
if (fout.fail())
{
cout << "Error";
exit(1);
}
if (fin.fail())
{
cout << "Error";
exit(1);
}
do
{
fin >> gname;
gamename.push_back(gname);
fin >> gconsole;
console.push_back(gconsole);
fin >> gstock;
stock.push_back(gstock);
fin >> gprice;
price.push_back(gprice);
} while(!fin.eof());
for (std::vector<string>::iterator it = gamename.begin(); it != gamename.end(); ++it)
{
sort(gamename.begin(), gamename.end());
gamename.erase(unique(gamename.begin(), gamename.end()), gamename.end());
cout << *it << endl;
*it=gedit;
}
cout << "Which game would you like to edit?n";
cin >> name;
if (name == gedit)
{
cout << SPACES << "a:NAMEn";
cout << SPACES << "b:CONSOLEn";
cout << SPACES << "c:STOCKn";
cout << SPACES << "d:PRICEn";
cin >> resp;
if ('a'==resp)
{
cout << "Type in the new namen";
cin >> new_name;
name=new_name;
}
}

我建议使用不同的数据结构,因为您正在尝试按名称访问项。vector(和数组)只能通过索引进行访问。一个可行的是地图(尤其是因为你希望它们是独一无二的)。

如果我理解你想正确地做什么,你可以用[console, stock, price]制作string(name)到vector<string>的映射。现在,您可以访问控制台、库存和价格(以及名称)。

所以你用很多<>初始化:)

map<string, vector<string>> games;

第一个字符串是名称,然后向量是控制台、股票和价格(所有字符串)。

读取文件时:

while (!fin.eof())
{
// We know it's 3 big. We could use a C array but why not use vector
vector<string> details(3);
for (int i=0; i<details.size(); ++i)
{
fin >> details[i];
}
}

在读取fin时,应该使用while循环而不是do...while来检查文件(0字节文件)乞讨时的eof。

你的中间循环很奇怪,我不确定你想要实现什么(对每个条目的列表进行排序,然后分配一个未定义的游戏名称?)但是,你可以通过循环map来打印每个游戏名称。这是可能的,但不像你对向量的期望:顺序不是你输入的(它们是为了速度而内部排序的)。

for (auto i = games.begin(); i != games.end(); i++)
{
cout << i->first;
}

映射迭代器(我使用C++11auto,因为它的typedef是long)指向包含firstsecondpairfirst是您的密钥(您的游戏名称)。second是另一部分(您的控制台、库存和价格)。

现在,您可以按名称快速访问游戏。这比搜索特定名称更具可扩展性。

auto game = games.find(name);
if ('a' == resp)
{
if (game != games.end())
{
cout << "Type in the new namen";
cin >> game->first;
}
}
else if (resp > 'a' && resp <= 'd')
{
// Here we can access the other data.
// To avoid writing so many conditionals we calculate the index.
// 'b' - 'b' is zero: console. Etc.
int index = resp - 'b';
cout << game->second[index];
}

附言:写得很快:这可能是错误百出。