【发布时间】:2014-09-22 17:24:28
【问题描述】:
我有一个提示用户输入命令的程序。根据命令,它会执行不同的功能。
示例命令:
help
set value 20
set another 30
print this
print that
如何将它们拆分为 3 个单独的变量并继续执行程序?我遇到了一个简单的问题
string command;
string item;
string value;
cin >> command >> item >> value;
因为除非用户输入所有三个,否则程序将无法继续。
这是我想出的,我无法回答自己的问题,所以可以这样做。
感谢您的意见。这是我在研究了@JoachimPileborg 提到的一些功能后得出的结论。它似乎就像我需要的那样工作。
int main() {
bool done = false;
char input[30];
std::string command, item, value;
//output instructions, get user input
std::cout << "Type 'help' to find more about commands.\n";
do{
std::cin.getline(input,30);
//parse user input from char to an array
istringstream iss;
string commands[3];
iss.str (input);
for (int i = 0; i < 3; i++) {
iss >> commands[i];
}
//set each part of the array to appropriate value
command = commands[0];
item = commands[1];
value = commands[2];
//properly sort out which command is being called
//first: check if command has 3 parts
if (commands[2].length() != 0){
cout << command << item << value;
}
//second:if it doesnt have 3 parts, check if it has 2 parts
else if (commands[1].length() != 0){
cout << command << item;
}
//third:if it doesn't have 2 parts, check for 1 part
else if (commands[0].length() != 0){
if (command == "help"){
commandline.help();
done = true;
}
else{
cout << "Incorrect Command! Please try again!";
}
}
else
cout << "No command found, please try again!";
}while(!done);
}
【问题讨论】:
-
在读取命令行等内容时不要使用输入运算符
>>。相反,我建议您使用std::getline,然后使用std::istringstream和std::copy将单独的字符串放入std::vector。 -
您可以将整行读入一个字符串,并根据空格分隔符拆分字符串。然后根据你的字符串分成多少个单词,从那里继续。
-
为了进一步帮助您,将命令名称和function objects 存储在
std::unordered_map中,然后很容易找到调用特定命令的函数。将包含命令行的向量作为参数传递给函数,类似于将argv传递给main函数的方式。 -
@Ben 如果有空格,如何将整行读入字符串?
-
@JoachimPileborg 我对 c++ 很陌生,我对这些函数中的任何一个都不是很熟悉,我会研究它们。你能提供任何例子吗?