等于在C ++中返回false [英] Equals returning false in c++
问题描述
我对cpp还是很陌生,我正在尝试做一个项目。它说代码必须以文件名作为参数,并将由以下命令运行:
I'm fairly new to cpp and I am trying to do a project. It says that the code must take in a filename as an argument and will be run by:
./main -i filename
我编写了一个for循环,该循环将遍历参数列表以查找 -i参数,以便我可以确定文件名。但是此行始终返回false:
I have written a for-loop that will iterate through the list of arguments to find the "-i" argument so that I can determine the filename. But this line always return false:
argv[i] == "-i"
下面是我的代码:
#include <string>
#include <iostream>
int main(int argc, char *argv[]) {
std::string test = argv[0];
for(int i = 0; i < argc; i++){
if(argv[i] == "-i"){
test = argv[i+1];
break;
}
}
std::cout << test;
return 1;
}
推荐答案
argv[i] == "-i"
在上面的行中比较两个指针:分别为 char *
和 const char *
。
In the line above you compare two pointers: char*
and const char*
, respectively.
换句话说,不是比较 argv [i]
和-i
两个指针,而是比较指向同一位置的可能性很小。结果,该支票在您的情况下不起作用。
In other words, instead of comparing argv[i]
and "-i"
two pointers are compared which are pretty much unlikely to point to the same location. As a result, the check doesn't work in your case.
您可以采用多种方式来修复它,例如,包装-i
放入 std :: string
以使比较正常工作:
You can fix it in multiple ways, for example wrap "-i"
into std::string
to make the comparison work properly:
const auto arg = std::string{ "-i" };
for(int i = 0; i < argc; i++){
if(argv[i] == arg){
test = argv[i+1];
break;
}
}
从 C ++ 17开始,您还可以使用 std :: string_view
:
Starting with C++17 you might also use a std::string_view
:
const std::string_view sv{ "-i" };
for(int i = 0; i < argc; i++){
if(argv[i] == sv){
test = argv[i+1];
break;
}
}
这是一种更好的方法,因为它避免了 std :: string
创建。
which is a preferable way as it avoids a std::string
creation.
这篇关于等于在C ++中返回false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!