【发布时间】:2015-04-13 23:20:53
【问题描述】:
这听起来很容易回答,但我不知道如何进行。我有一组函数放在一起来控制一个行编辑器,但是每个函数对行编辑器做事都有不同的影响。
无论如何,例如...我有一个名为“setfilename”的函数。我想创建一个用户必须输入的命令才能使用他的特定文件名调用它。
例如,要调用“setfilename”的命令应该是“r filename " 代表“读取文件名”
用户必须输入“r test”才能读取测试文件名。
这清楚吗?我怎么能这样做?会有一个我想要的命令列表,每个命令都会调用不同的函数。
列表:
string choice;
cout << "What command would you like to perform?" << endl;
cout << "r filename" << endl;
cout << "w filename" << endl;
cout << "q" << endl;
cout << "s n" << endl;
cout << "s m n" << endl;
cout << "i n" << endl;
cout << "l n" << endl;
cout << "d n" << endl;
cout << "d n m" << endl;
cout << "c n" << endl;
cout << "c n m" << endl;
cout << "p n" << endl;
cout << "P n" << endl;
cout << "f string" << endl;
cout << "F string" << endl;
cout << "x string1 string2" << endl; // bonus
while (true)
{
cout << "INPUT: -> ";
cin >> choice;
if (choice=="r filename")
{
setfilename(choice)
}
else if (choice == "w filename")
{
...
}
else if (choice == "quit")
{
break;
}
}
【问题讨论】:
-
和
std::getline() -
例如,我想输入“r test”,但我不希望我的文件名被称为 r test。它应该是“测试”。所以你的答案不是我想要的。
-
是的,这就是答案。循环调用
std::getline()。它会给你一个std::string。然后,您只需根据需要拆分该值,例如使用std::string::find()和std::string::substr(),并根据需要处理子字符串。如果您不知道如何简单地进行string解析,那么您需要停止您正在做的任何事情,回到基础。这是 C++ 的一项基本技能。 -
啊,我明白了。谢谢。
-
您可以先读入命令,检查其值以查看命令是什么,然后再读入其参数,因为不同的命令具有不同数量和类型的参数。