我有一个接受用户输入的程序,它可以是 5 个字符的命令,如“help”,也可以支持标志类型的命令,如“delete -p 'George'”
我对 C++ 的经验不多,除了做了一堆 for 循环,想知道是否有更有效的方法来解析 char 数组。
有人能给我指出正确的方向吗?
最佳答案
除了评论中建议的 boost 库之外,如果您正在解析相对较小的参数集,您可以使用简单的 std::cin
在程序运行时接收参数,一些喜欢:
#include <iostream>
#include <string>
#include <vector>
int main() {
std::vector<std::string> args;
std::string arg;
while(std::cin >> arg) {
args.push_back(arg);
}
}
上面需要一个 EOF(不是回车)来标记命令的结束。
要使用回车标记命令结束,您需要 getline()
,如下所示:
std::vector<std::string> get_args() {
using std::string;
using std::stringstream; // don't forget to include <sstream> header
string line;
getline(std::cin, line);
stringstream ss;
ss << line;
std::vector<string> cmds;
string cmd;
while (ss >> cmd) {
cmds.push_back(cmd);
}
return cmds;
}
或者如果您希望您的主函数接受参数:
int main(int argc, char **argv) {
// The call to the excutable itself will be the 0th element of this vector
std::vector<std::string> args(argv, argv + argc);
}
关于c++ - 在没有 for 循环的情况下解析字符串的字符数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46655379/