Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
456 views
in Technique[技术] by (71.8m points)

g++ - Equals returning false in c++

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

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"

Below is my code:

#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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
argv[i] == "-i"

In the line above you compare two pointers: char* and const char*, respectively.

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.

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;
    }
}

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;
    }
}

which is a preferable way as it avoids a std::string creation.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...