0

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?

Stwosch
  • 602
  • 1
  • 7
  • 20
  • 2
    What is `n[i]`? Is it a `std::string` object? Did you really *read* the error message (whatever it is)? Perhaps you should [find a good beginners book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) and start learning C++ properly? – Some programmer dude Apr 08 '17 at 13:59
  • 1
    `n[i]` is a char. (Not a `string` of size 1). `char` does not have member functions. – M.M Apr 08 '17 at 14:01
  • It's unclear what exactly you are trying to achieve - do you want to convert the entire number described by your string to an `int` (in which case you'd simply use `x = std::stoi(n);` ([reference](http://en.cppreference.com/w/cpp/string/basic_string/stol)) or do you want to perform some calculation with each digit of that number? – UnholySheep Apr 08 '17 at 14:10
  • [don't use `atoi`](http://stackoverflow.com/q/17710018/995714). It's [harmful](https://blog.mozilla.org/nnethercote/2009/03/13/atol-considered-harmful/) – phuclv Apr 08 '17 at 14:54

1 Answers1

4

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';
Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
  • In case someone is wondering over the `char` to integer promotion in the final snippet, the `'0'` subtraction simply shifts the ASCII value of `n[i]` by `48`, since character values of digits starts (and, as mentioned above, continuous sequentially, increasing) at ASCII value `48` (for `'0'`). – dfrib Apr 08 '17 at 14:33
  • @dfri It shifts the value of `n[i]` by the value of the literal `'0'`. That is 48 when the system is using ASCII, but it can be anything else in other encodings. The point is that it must always work such that `'1' - '0' == 1` (and similar for other digits). – Angew is no longer proud of SO Apr 08 '17 at 14:40
  • I didn't consider non-ASCII systems, thanks for the clarification! Your comment above (especially core-point the last sentence) might valuable to include in the answer for those of us that didn't entirely catch this. – dfrib Apr 08 '17 at 14:42