some_math_guy
some_math_guy

Reputation: 333

Substracting a string from an int

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?

Upvotes: 0

Views: 95

Answers (2)

DFChelsea
DFChelsea

Reputation: 1

First,strchr returns a pointer.Pointrer types require a forced cast. Second,The data type of the pointer is related to the number of CPU bits.So you should use unsigned long type.

Upvotes: 0

SchweizS
SchweizS

Reputation: 44

.c_str() returns the address to the start of the string. strchr the address to the first occurence of a specific character inside the given string or a nullptr, if the character is not found.

If you subtract one address from another, you get the distance of the to pointers, which is the offset of the character inside the string in this case.

The find_* functions of the string class all return the offset or std::string::npos, if the character is not found.

Reference:

Upvotes: 2

Related Questions