主要论点处理的问题
Issue with main arguments handling
我无法将main()
参数与const char*
字符串进行比较。
简单的解释代码:
#include <stdio.h>
int main(int argc, char *argv[])
{
int i;
if(argc>1)
{
for (i=1;i<argc;++i)
{
printf("arg[%d] is %sn",i,argv[i]);
if(argv[i]=="hello")
printf(" arg[%d]=="hello"n",i);
else
printf(" arg[%d]!="hello"n",i);
}
}
return 0;
}
简单的编译g++ test.cpp
。当我尝试执行它时,我会看到下一件事:
>./a.out hello my friend
arg[1] is hello
arg[1]!="hello"
arg[2] is my
arg[2]!="hello"
arg[3] is friend
arg[3]!="hello"
我的代码怎么了?
无法与==
进行比较,使用strcmp:
if (strcmp(argv[i], "hello") == 0)
您必须进行#include <string.h>
每当您使用argv [i] ==" hello"时,操作员" ==" donot将字符串作为操作数,因此在编译器中,编译器将指针与argv [i]进行比较恒定字符串" hello"的指针总是false,因此您获得的结果是正确的,要比较字符串文字使用SRTCMP函数。 int strcmp(const char *s1,const char *s2);比较了两个字符串S1和S2。它返回一个整数小于,等于或大于零,如果发现S1的数量小于匹配或大于S2。
在此语句中
if(argv[i]=="hello")
您比较指针,因为字符串文字被隐式转换为指向其第一个字符的const char *(或char *)。由于两个指针具有不同的值,因此表达式始终是错误的。您必须使用标准的C函数strCMP。例如
if( std::strcmp( argv[i], "hello" ) == 0 )
要使用此功能,您应该包括标题<cstring>
(在C 中)或<string.h>
(在C)中。
相关文章:
- 警告处理为错误这里有什么问题
- posix_spawn():使用posix_scawn()时的错误处理问题
- 当我使用 C++ 中的 C# dll 来使用 Selenium 时,存在异常处理问题
- C++:处理抽象类中的错误时出现问题
- 在通知提升间处理条件变量时未按住锁会导致问题
- 如何在 cpp 中使用 std::enable_if 从模板中处理此类问题
- wxWidgets 拖放文件事件处理程序初始化问题(无效static_cast)
- 关于 istream 中的错误处理的问题
- 有关如何处理 vulkan 队列系列的问题
- 我如何处理这种情况C++大小问题
- 在C++中做一个场景问题,我不确定如何处理布尔和if循环
- 用wchar_t处理 unicode 字符好吗?它不会引起任何问题吗?
- 关于 ocilib 错误处理的问题,如何使用 ocilib 正确捕获日志错误?
- Eclipse 问题 - 编译期间不考虑 .c 和 .cpp 文件中定义的预处理
- STD :: FSTREAM文件处理重复使用的问题
- 在 cplex c++ 音乐会 api++ 中处理非常大的问题而不会耗尽内存
- 使用 ARDUINO 和处理在 8x8 LED 矩阵上显示数据时出现问题
- googlemock - 如何处理"多重定义"问题?
- 指纹读取器 - 从 C# 代码创建事件处理程序到C++的问题
- 问题处理缺点引用另一个类中的类