I following code illustrates the use of c_str function
#include <iostream>
#include <string.h>
using namespace std;
int main() {
std::string str("Hello world!");
int pos1 = str.find_first_of('w');
cout<< "pos1: "<< pos1 <<endl;
int pos2 = strchr(str.c_str(), 'w') - str.c_str(); //*
//int pos2 = strchr(str.c_str(), 'w')
cout<< "pos2: "<< pos2 <<endl;
cout<< "str.c_str(): "<< str.c_str() <<endl;
if (pos1 == pos2) {
printf("Both ways give the same result.\n");
}
}
The output is
pos1: 6
pos2: 6
str.c_str(): Hello world!
Both ways give the same result.
I don't get the str.c_str() role in line *
. I am substracting a string from an int, what is the meaning of that?
When I erase it, that is when I comment line *
, and uncomment the following line I get an error: invalid conversion from 'char*' to 'int'. How come there is not error in the original code?