0

EDIT :- How his question is different than Getting a character from a string is returning an unexpected number?

  1. The technology specified there is C#, not c++.
  2. The question associates list box, while mine was associating a vector, and string.

I am trying to push a string full of integers with the help of string iterator in my c++ integer vector (vector), but unfortunately when I push the de-referenced string, all I get are some garbage value being pushed in my vector.

I tried searching google for days. Alongside that, I've tried looking documentations, and I've also tried to force convert the de referenced string iterator using (int).

#include <iostream>
#include <vector>
#include <string>
using namespace std;




int main() {
    string str = "1234";
    vector<int> vec;

    for (string::iterator itr = str.begin(); itr != str.end(); ++itr){         
        vec.push_back(*itr);

    }
    for (vector<int>::iterator itr = vec.begin(); itr != vec.end();      
    ++itr) {
         cout << *itr;
    }

    return 0;
}

Expected output : 1234


Actual output : 49505152

1 Answers1

2

You are not seeing "garbage values", but rather the numerical values of the characters in the string. That is, because you are using an ASCII system like the vast majority of people, the value of the character '1' is 49, and so on. If you want to convert a digit character, such as '1', to the integer, such as 1, you need to subtract '0' (which would be 48 on your system).

Brian Bi
  • 111,498
  • 10
  • 176
  • 312
  • Hi thanks for the answer! Is there any alternative, won't subtracting zero every-time in my code make my code look ugly? – TheMightyBarbarian May 01 '19 at 14:17
  • @NeelMishra what are you _actually_ trying to achieve? If you have a string `"1234"` and you want to transform this into a `vector` containing the `int` values 1,2,3 and 4, then you need to substract `'0'` – Jabberwocky May 01 '19 at 14:19
  • @NeelMishra I don't know what you mean by "ugly", but normally, your code should not be littered with this conversion since you should only perform it at the point where "input" is converted into an internal representation. – Brian Bi May 01 '19 at 14:19
  • @NeelMishra This answers how to actually implement the behavior you want. There's a general consensus that it is the best way of doing it for the general case. If you find it ugly, feel free to hide it in a function. Then you can do, for example `vec.push_back(char_to_int(*itr));`. But `x - '0'` is a well known idiom in c++. Experienced developers will immediately recognize the pattern for what it is. – François Andrieux May 01 '19 at 14:29