【发布时间】:2014-07-27 05:34:18
【问题描述】:
我正在根据我的教科书做一个练习,让我创建一个程序,该程序允许用户通过添加、删除或查看向量中的项目来管理最喜欢的游戏列表。我利用了函数;我的程序运行,但功能似乎没有做他们应该做的。我可以为 addGame() 输入游戏名称,但是当我在 do/while 循环中输入 4 时,没有打印任何向量。同样,removeGame() 函数似乎不起作用,因为如果我输入不在列表中的游戏,它不会显示任何消息。
没有显示是哪个功能的问题?两者或只有一个(addGame 或 dispGames)?为什么我的 removeGame 功能不起作用?
感谢您的帮助。
// exercises ch 4.cpp : main project file.
#include "stdafx.h"
#include<iostream>
#include<string>
#include<vector>
#include<iterator>
using namespace std;
void addGame(vector<string> faveGames);
void removeGame(vector<string> faveGames);
void dispGames(vector<string> faveGames);
int main(array<System::String ^> ^args)
{
vector<string> faveGames;
int choice;
cout << "Welcome to the Favorite Games List program!\n\n";
do
{
cout << "What would you like to do?\n\n";
cout << "1 - End program. \n 2 - Add new game to list. \n 3 - Remove game from list. \n 4 - Display list. \n";
cout << "Enter the corresponding number of your choice: ";
cin >> choice;
switch (choice)
{
case 1: cout << "Ending program.\n"; break;
case 2: addGame(faveGames) ; break;
case 3: removeGame(faveGames); break;
case 4: dispGames(faveGames); break;
default: "That is not a valid response, please try again.";
}
}
while(choice != 1);
return 0;
}
void addGame(vector<string> faveGames) {
string newFaveGame;
cout << "Enter the name of the game you want to add: ";
cin >> newFaveGame;
faveGames.push_back(newFaveGame);
}
void removeGame(vector<string> faveGames) {
vector<string>::iterator deletedGameIter;
string deletedGame;
cout << "Enter the name of the game you want to delete: ";
cin >> deletedGame;
for(deletedGameIter = faveGames.begin(); deletedGameIter != faveGames.end(); ++deletedGameIter) {
if(deletedGame == *deletedGameIter) {
faveGames.erase(deletedGameIter);
}
else
{
cout << "That game is not on your list.\n";
}
}
}
void dispGames(vector<string> faveGames) {
vector<string>::iterator iter;
for(iter = faveGames.begin(); iter != faveGames.end(); ++iter)
{
cout << *iter << endl;
}
}
【问题讨论】:
-
你应该使用
deletedGameIter->compare(deletedGame) == 0不是你的问题,而是一些有趣的建议。 -
在你的函数中通过引用发送向量,你现在是按值发送它们,所以你可能没有修改任何东西。
-
@Ben,不,不是
std::string。这只会让阅读变得更加困难。 -
这甚至不是 C++。是 C++/CLI 还是 C++/CX,请正确重新标记问题。
标签: string function vector iterator c++-cli