Equals returning false in c++

2020-08-10 06:18发布

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

3条回答
不美不萌又怎样
2楼-- · 2020-08-10 06:35

You cannot compare pointers to char to string literals (char const*) using ==. Use std::strcmp() (<cstring>) or construct a std::string (<string>) from it to make it comparable to a char* using ==.

查看更多
放我归山
3楼-- · 2020-08-10 06:47
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.

查看更多
Lonely孤独者°
4楼-- · 2020-08-10 06:47

try this:

#include <iostream>
#include <string>
using namespace std;
int main(int argc, char *argv[]) {
    string test;
    for(int i = 0; i < argc; i++){        
        cout << "\n" << argv[i] << endl;
        if((string)argv[i] == "-i"){
            test = argv[i + 1];
            cout << "test= " << test << endl;
            break;
        }
    }
    cout << test << endl;
    system("pause");
    return 0;
}
查看更多
登录 后发表回答