Using argv in C?

前端 未结 6 1336
难免孤独
难免孤独 2020-12-03 22:37

For an assignment, I am required to have command line arguments for my C program. I\'ve used argc/argv before (in C++) without trouble, but I\'m unsure if C style strings ar

相关标签:
6条回答
  • 2020-12-03 22:42

    The prototype of the main function says you're dealing with char* pointers. In C, there is no operator overloading; therefore, == between two char* will test if they point to the same place. This is not the case, and is rarely the case at all. Use the strcmp (the reference for the function is valid even though it points to a C++ site) function from <string.h>:

    strcmp(argv[1], "-e") == 0
    
    0 讨论(0)
  • 2020-12-03 22:49

    You can't use == to compare strings like that in C. That's just comparing the addresses of argv[1] and your literal, which are pretty much guaranteed to be different.

    Use strcmp instead. eg:

    if (!strcmp("-e", argv[1])) {
    
    0 讨论(0)
  • 2020-12-03 22:50

    The line

    if(argv[1]=="-e"){
    

    compares pointers, not strings. Use the strcmp function instead:

    if(strcmp(argv[1],"-e")==0){
    
    0 讨论(0)
  • 2020-12-03 23:00

    Change:

    if(argv[1]=="-e"){
    

    to

    if(strcmp(argv[1], "-e") == 0){
    

    and include string.h.

    0 讨论(0)
  • 2020-12-03 23:04

    You can't compare c-strings like that. Use strcmp (reference here).

    Because c-strings are actually pointers, the == operator compares the address of the first character which will never be equal in this case.

    0 讨论(0)
  • 2020-12-03 23:05

    Check out getopt() and related functions; it'll make your life a lot easier.

    0 讨论(0)
提交回复
热议问题