strcmp[c++] error: invalid conversion from ‘char’ to ‘const char*’ [-fpermissive]

StackOverflow https://stackoverflow.com/questions/20773143

  •  21-09-2022
  •  | 
  •  

質問

Where am doing wrong in this code? I need only in char types, please don't suggest to use std::string.

#include <iostream>
#include <string.h>
using namespace std;

int main() 
{
    char *mystring="C:/windows";
    char last_char;
    last_char = mystring[strlen(mystring)-1];
    cout<<"Input: " <<mystring<<endl;
    if(strcmp(last_char,";")!=0)
    {
        strcat(mystring,";");
    }
    cout<<"Output: "<<mystring<<endl;
    return 0;
}

Output:

    Compilation error    time: 0 memory: 3340 signal:0
prog.cpp: In function ‘int main()’:
prog.cpp:7:17: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]
  char *mystring="C:/windows";
                 ^
prog.cpp:11:25: error: invalid conversion from ‘char’ to ‘const char*’ [-fpermissive]
  if(strcmp(last_char,";")!=0)
                         ^
In file included from prog.cpp:2:0:
/usr/include/string.h:140:12: error:   initializing argument 1 of ‘int strcmp(const char*, const char*)’ [-fpermissive]
 extern int strcmp (const char *__s1, const char *__s2)
役に立ちましたか?

解決

Don't use strcmp, it expects a null terminated characters sequence. Instead, use direct comparison:

if (last_char == ';') ...

Also, your code invokes undefined behavior in the strcat() call. my_string was initialized with a string literal, thus, you are not allowed to modify it, since the implementation is free to place it in read-only memory (and typically will do so).

You can declare it like this instead:

char mystring[12] = "C:/windows"; // space for one more char

他のヒント

last_char is not a string. It is a character. You can't compare a char with string.
Try this instead

 if (last_char == ';') {...}  

Statement

 strcat(mystring,";");

invokes undefined behavior. You can't modify a string literal as it resides in read only section of the memory.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top