C++을 사용하고 있으므로 std :: string에서 C와 유사한 문자열을 모두 변환 할 수 있습니다. 이 작업은 프로그램 시작시 한 번 수행되므로 효율성 문제는 없습니다.
//Somewhere near the top of main()
bool itemFound(false);
for(int i=1; i<argc; ++i) {
if(std::string(argv[i]) == std::string("--item")) {
itemFound = true;
//And remove this item from the list
argv[i][0] = 0; //Transform it in an empty string, putting null as first character
}
}
//Now, use argc/argv as normal, knowing that --item is not in there
그렇지 않으면 (변수는 argv와 해킹 방지) :
는
std::vector<std::string> validArgs;
validArgs.reserve(argc); //Avoids reallocation; it's one or two (if --item is given) too much, but safe and not pedentatic while handling rare cases where argc can be zero
for(int i=1; i<argc; ++i) {
const std::string myArg(argv[i]);
if(myArg != std::string("--item"))
validArgs.push_back(myArg);
}
어떤 이유로 당신은 여전히 itemFound이 필요한 경우는 경우 블록에 설정할 수 있습니다.
(참고 : 하나의 문 블록이있을 때 이것은 앓은 주제 : https://softwareengineering.stackexchange.com/questions/16528/single-statement-if-block-braces-or-no하지만 당신이, 중괄호가 필요하지 않습니다)
편집 (표준 사이의 비교 연산자의 존재를 돌보는 : : 문자열과 문자 *)
bool itemFound(false);
for(int i=1; i<argc; ++i) {
if(std::string("--item") == argv[i]) {
itemFound = true;
//And remove this item from the list
argv[i][0] = 0; //Transform it in an empty string, putting null as first character
}
}
또는
:
std::vector<std::string> validArgs;
validArgs.reserve(argc); //Avoids reallocation; it's one or two (if --item is given) too much, but safe and not pedentatic while handling rare cases where argc can be zero
for(int i=1; i<argc; ++i)
if(std::string("--item") != argv[i])
validArgs.push_back(std::string(argv[i]));
사용의 strcpy (는 argv [I] ' "); –
먼저 데이터 구조를 일종의 데이터 구조에 복사하는 것이 좋습니다. 그렇지 않으면 Nishith의 해결책이 효과가있을 수 있습니다 – woosah
'std :: vector args (argv, argv + argc); ' –