Slu*_*ips 3 c++ command-line arguments
好吧,我正试图通过小型测试应用程序使参数正常工作.我的代码如下.我对C++没有太多经验,所以我不确定为什么当我用-print(或--print)启动测试时它会自动声明"Not a valid option"然后结束.
#include <iostream>
int main(int argc, char* argv[])
{
int option;
option = 1;
char* argument;
argument = argv[option];
while (option < argc)
{
if (argument == "-print")
{
std::cout << "Printing Extra Text";
}
else
{
std::cout << "Not a valid option" << std::endl;
}
option++;
}
std::cout << "Printing normal text" << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我这样做了吗?提前致谢.
gak*_*gak 12
您将字符串"-print"的内存地址与内存地址进行比较argument
.这不行!使用strcmp()
来比较两个字符串值.代替:
if (argument == "-print")
Run Code Online (Sandbox Code Playgroud)
做
if (strcmp(argument, "-print") == 0)
Run Code Online (Sandbox Code Playgroud)
以下行有错:
if (argument == "-print")
Run Code Online (Sandbox Code Playgroud)
在这里,您要比较指针,而不是字符串值.用...来代替:
if (strcmp(argument, "-print") == 0)
Run Code Online (Sandbox Code Playgroud)
对于字符串处理,C/C++的行为与Java或C#不同.字符串不是本机类型或对象,而只是美化指向字符数组的指针.
或者,如果您的选项列表变得更复杂,请考虑使用专用选项解析库,例如Boost的Program_options.它将处理所有方面,包括验证和用户消息.