等于在 C++ 中返回 false
我对 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.
相关文章