I want to do something with string using the index
and rindex
function under c++17, but when I compile the program, this error poped up:
debug.cpp: In function ‘int main()’:
debug.cpp:7:27: error: invalid conversion from ‘const char*’ to ‘char*’ [-fpermissive]
7 | char* index_first = index(str,'c');
| ~~~~~^~~~~~~~~
| |
| const char*
debug.cpp:9:27: error: invalid conversion from ‘const char*’ to ‘char*’ [-fpermissive]
9 | char* index_last = rindex(str,'c');
| ~~~~~~^~~~~~~~~
| |
| const char*
Then I checked this program online, every function defines of index
and rindex
I saw are the same:
char* index(const char* s,int c);
char* rindex(const char* s,int c);
And heres my debug code:
#include <stdio.h>
#include <string.h>
int main()
{
const char* str = "abcdefgabcdefg";
char* index_first = index(str,'c');
printf("the first index is %ld\n",index_first - str + 1);
char* index_last = rindex(str,'c');
printf("the last index is %ld\n",index_last - str + 1);
return 0;
}
I compile it using:
g++ -o debug debug.cpp -std=c++17
I want to know why can't I do that and the right way to use index
and rindex
functions and (or) the right function defines please.
Heres my environment:
Ubuntu LTS 20.04 (x64)
g++ (Ubuntu 9.4.0-1ubuntu1~20.04.1) 9.4.0
Thank you for all the help.
You are trying to assign returned pointers of the type
const char *
that are used within the functions to pointers of the typechar *
Actually the functions you are calling are declared like
In C++ the functions can be overloaded like
and
the same way as some other standard C functions as for example the standard C function
strchr
.So you should write
The result of subtracting two pointers has the signed integer type
ptrdiff_t
. So you need to use the conversion specifier%td
instead of%ld
.From the C Standard (7.21.6.1 The fprintf function)