store a string to an integer array

Dec 22, 2015 at 1:29pm
Hey I'm a beginner in C++. I want to read a number(8-10 digits) as a string and then copy it into an integer array but I have no idea how to do it.

Last edited on Dec 22, 2015 at 1:29pm
Dec 22, 2015 at 1:34pm
copy it into an integer array

You mean copy individual digits of the string to the array?

Or do you mean copy the entire number as an integer to a single element of the array?
Dec 22, 2015 at 1:35pm
You'll want to convert from string to int, many ways of doing this. Read this thread - http://www.cplusplus.com/forum/general/13135/
Dec 22, 2015 at 1:39pm
You mean copy individual digits of the string to the array?

Or do you mean copy the entire number as an integer to a single element of the array?

I want to store each digit in an element
Dec 22, 2015 at 2:25pm
Thanks. Well, to convert from a character such as '5' to an integer, this will work:
1
2
char ch = '5';
int num = ch - '0';

That is, subtract the character zero from the digit character to get its value as an integer.

To store in an array,
1
2
3
4
string input = "76543";
int array[30];
for (int i=0; i<input.size(); i++)
    array[i] = input[i] - '0';


Topic archived. No new replies allowed.