帮忙看一个main参数的有关问题
帮忙看一个main参数的问题
源程序如下:
#include <iostream>
#include <string>
using namespace std;
int main(int argc, char** argv) {
if (argc != 2) {
cout << "wrong number of inputs" << endl;
exit(1);
}
string test = "dream";
cout << "is test equal to \"dream\"? " <<(test == "dream")<< endl;
cout << "is argv[1] equal to \"dream\"?" << (argv[1] == "dream")
<< endl;
cout << "is argv[1] equal to test?" << (argv[1] == test) << endl;
return 0;
}
在命令行中敲入:commandname dream
结果为:
is test equal to "dream"? 1
is argv[1] equal to "dream"?0
is argv[1] equal to test?1
既然 argv[1]和equal相等,equal和“dream”相等,那么argv[1]和“dream”为什么不等呢?
------解决方案--------------------
argv[1]是char*类型不能和“dream”直接==来判断的,应该是strcmp(argv[1], "dream") == 0来判断;
或者:
strring strArgv1 = argv[1];
strArgv1 == "dream";
源程序如下:
#include <iostream>
#include <string>
using namespace std;
int main(int argc, char** argv) {
if (argc != 2) {
cout << "wrong number of inputs" << endl;
exit(1);
}
string test = "dream";
cout << "is test equal to \"dream\"? " <<(test == "dream")<< endl;
cout << "is argv[1] equal to \"dream\"?" << (argv[1] == "dream")
<< endl;
cout << "is argv[1] equal to test?" << (argv[1] == test) << endl;
return 0;
}
在命令行中敲入:commandname dream
结果为:
is test equal to "dream"? 1
is argv[1] equal to "dream"?0
is argv[1] equal to test?1
既然 argv[1]和equal相等,equal和“dream”相等,那么argv[1]和“dream”为什么不等呢?
------解决方案--------------------
argv[1]是char*类型不能和“dream”直接==来判断的,应该是strcmp(argv[1], "dream") == 0来判断;
或者:
strring strArgv1 = argv[1];
strArgv1 == "dream";