我有一個程序,它在用戶輸入其範圍可以從像「幫助」 5字符的命令,並還支持像「刪除-p‘喬治’」爲沒有for-loops的字符串解析字符數組?
我沒有旗型命令除了做一堆for循環外,很多C++的經驗都在想知道是否有更有效的方法來解析char數組。
難道有人指着我正確的方向嗎?
我有一個程序,它在用戶輸入其範圍可以從像「幫助」 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
@ user1692517如果我的回答對您有幫助,請接受答案或向上提問,謝謝。 – aghilpro
聽起來像是你要解析命令行選項,檢查出['提振:: program_options'(http://www.boost.org/doc/libs/1_63_0/doc/html/program_options/tutorial .html#idp523371328) – CoryKramer
您正在尋求一種「更有效的方式」。比什麼更有效,你目前的解決方案是什麼? – opetroch