c++中的C字符串比较问题
我在 C++ 程序中进行比较时遇到了麻烦。这是精简版本。
#include "stdafx.h"
#include <iostream>
#include <windows.h>
using namespace std;
int main(int argc, char *argv[])
{
if(argc>2){cout<<"3+Args"<<endl;}else//???
if(argc==2){
cout<<"2args"<<endl;
if(argv[1]=="/hide-icons"){}
if(argv[1]=="/show-icons"){}
if(argv[1]=="/reinstall"){setAsDefault();}
if(argv[1]=="/?"){showPossibleCommands();}
if(argv[1]=="/1"){cout<<"go"<<endl;FirstRun();}
}else{showPossibleCommands();cout<<argv[0]<<endl;}
return 0;
}
当我运行“programname.exe /1”时,我的程序写入“2args”,但不写入“go”。我错过了一些明显的东西吗?
I've been having trouble with comparison in my c++ program. This is the boiled down version.
#include "stdafx.h"
#include <iostream>
#include <windows.h>
using namespace std;
int main(int argc, char *argv[])
{
if(argc>2){cout<<"3+Args"<<endl;}else//???
if(argc==2){
cout<<"2args"<<endl;
if(argv[1]=="/hide-icons"){}
if(argv[1]=="/show-icons"){}
if(argv[1]=="/reinstall"){setAsDefault();}
if(argv[1]=="/?"){showPossibleCommands();}
if(argv[1]=="/1"){cout<<"go"<<endl;FirstRun();}
}else{showPossibleCommands();cout<<argv[0]<<endl;}
return 0;
}
When I run "programname.exe /1", my program writes "2args" but not "go". Am I missing something obvious?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
argv[1]
是一个char*
,因此通过使用==
进行测试,您可以检查指针是否指向与您正在使用的各种字符串常量的开始...情况并非如此。 要比较内容,请使用 strcmp 。argv[1]
is achar*
, so by testing with==
you're checking if the pointer points to the same spot as the start of the various string constants you're using... which is not going to be the case. To compare contents instead, use strcmp.问题是,您的代码将指针与字符串进行比较,而不是字符串本身。
您必须将比较替换为对字符串比较函数的调用。
例如
,
您可能必须包含 string.h 才能将 strcmp 原型添加到代码中。
The problem is, that your code compares the pointers to the strings, not the stings itself.
You have to replace the compares with calls to the string-compare function.
E.g.
becomes
You may have to include string.h to get the strcmp prototype into your code.
另一种选择是将 C 风格的参数转换为更友好的字符串向量并对其进行处理:
Another option is to convert the C-style arguments into a much more friendly vector of strings and process them instead: