why does this happen?

when i enter this code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include <sstream>
#include <vector>


using namespace std;


int main ()
{ 
string Text = "45699999";
cout << Text.length() << "AsdasD"; 

vector <int> Result (Text.length());         t

istringstream convert(Text);
for (int i = 0; i <= Text.length()-1; i++)
{
convert >> Result[i];
cout << Result[i];
}


}


i get this output:

8AsdasD456999990000000
]

where do i get the extra zeros? i tried to make them go away but i can't
make Result an int instead of a vector. Should remove them
line 22 pulls out a full integral number, not a single digit. It sees 45699999 as one number, not as 8 digits.

So the first time that loop runs, you pull out the number 45699999 and print it.

After that, 'convert' is empty, so you get 7 crap numbers (in this case zeros) each time the loop repeats.
im trying to store each element of the string into a vector so that i can add the numbers individually. im not really looking for advice on implementation, im just curious why this happens.

edit:....nvm, i just figure out why, it adds the whole string into one vector element, so the rest are empty

anyone know how to add each element of this string into each element of the vector? for ex Result[0] = 4 and Result[1] = 5 and so on. cause right now, its doing Result[0] = 45699999


Here's a quick 'n' dirty way that just assumes 'Text' contains nothing but numerical digits '0' - '9'

1
2
3
4
5
string Text = "45699999";
vector<int> Result(Text.length());

for(int i = 0; i < Text.length(); ++i)
  Result[i] = Text[i] - '0';
The simplest way I can think of is converting each character in the string into a digit and sticking that into an array of ints (or vector if you prefer).
'Number Character' - '0'
would give you a value 0-9.

Edit: Beaten to the punch I see
Last edited on
wow amazing how just a little change makes it works and i hear i was going completely crazy and was going to try a whole different way. i guess istringstream and the "convert>>Result" was useless.

but can i asked why you did -'0'? i mean it works but i want to know why. cause if i just removed only the -'0'. i would get some crazy number.

edit: if i do not do the -'0' the output is just the ascii value of those nums, why does -'0' work?
-'0' means subtracting 48, which is the ascii value of character '0'. so if '1'=49 then 49-48=1
i see....but i did not know that you could subtract character from vector element which contained an int. that's cool.

does this mean i can declare something like:
int a = 90;
char b = 'p';
cout << a-b;

would that subtract 90 from the asci value of p or would it not work at all?
edit: i just tried it, it works. wow i didn't know this, im soooo noob
Topic archived. No new replies allowed.