为没有for-loops的字符串解析字符数组?
问题描述:
我有一个程序,它在用户输入其范围可以从像“帮助” 5字符的命令,并还支持像“删除-p‘乔治’”为没有for-loops的字符串解析字符数组?
我没有旗型命令除了做一堆for循环外,很多C++的经验都在想知道是否有更有效的方法来解析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);
}
答
是的,你可以像这样分配一个字符数组到字符串:
char array[5] = "test";
string str (array);
cout << str;
输出:
test
+0
@ user1692517如果我的回答对您有帮助,请接受答案或向上提问,谢谢。 – aghilpro
听起来像是你要解析命令行选项,检查出['提振:: program_options'(http://www.boost.org/doc/libs/1_63_0/doc/html/program_options/tutorial .html#idp523371328) – CoryKramer
您正在寻求一种“更有效的方式”。比什么更有效,你目前的解决方案是什么? – opetroch