Stwosch
Stwosch

Reputation: 642

conversion between types in c++

I come from other programming languages and I don't understand why this code throws error.

string n = "123456";
int x;

for(int i = 0; i < n.length(); i++) {

    x = atoi( n[i].c_str() );
    x *= 2;
    cout << x << endl;
} 

Can you explain me this accident? And show me how to convert it into integer properly?

Upvotes: 0

Views: 58

Answers (1)

Look at the return type of std::basic_string::operator[]: it's reference or const_reference. That is, a (const) reference to a character. In the case of std::string, it means you get a reference to a char, not a std::string.

C++ guarantees that the character values of digits are sequential and increasing. In other words, it's guaranteed that '1' - '0' == 1, '2' - '0' == 2 and so on, regardless of character encoding used. So the way to convert the char containing a digit into the digit's value is to do just this:

x = n[i] - '0';

Upvotes: 4

Related Questions