hi, i am a newbie and i just started to learn C++.
My question is , if i put a number like 45678 in char x[6] then how do i separate each number and put it into int num[6].

Recommended Answers

All 4 Replies

somthing like this:

#include <iostream>

int main ()
{
    char c[6] = "45678";
    int num[5];
    for (int i = 0; i < 5; i++)
    {
        char temp = c[i];
        num[i] = atoi(&temp);
        std::cout << num[i] << std::endl;
    }
    system("pause");
}

Thank you , why do i have to do this??? can anyone pls explain??

num = atoi(&temp);

somthing like this:

#include <iostream>

int main ()
{
    char c[6] = "45678";
    int num[5];
    for (int i = 0; i < 5; i++)
    {
        char temp = c[i];
        num[i] = atoi(&temp);
        std::cout << num[i] << std::endl;
    }
    system("pause");
}

This code is downright dangerous. Suppose I add one line that seems not to affect the outcome:

#include <iostream>

int main ()
{
    char c[6] = "45678";
    int num[5];
    for (int i = 0; i < 5; i++)
    {
        char temp = c[i];
        char khan = '9';
        num[i] = atoi(&temp);
        std::cout << num[i] << std::endl;
    }
}

On my system, I get 49 59 69 79 89 with this code. Why?

This happens because temp is just a single character. You don't know what goes after it. When you pass a pointer of temp to atoi, atoi will expect a pointer to an _array_ of characters. It will read numbers until it gets a nondigit -- a character that is not in the range '0' .. '9'.

When you ran your code, you got lucky. The position in memory next to wherever temp was stored did not have an ASCII digit.

With my code example, you might get different output, since the result is affected by where your compiler puts everything.

Since khan may get stored right next to temp in memory, atoi might think it's the next character in the string, and so it reads 49, 59, and so on.

If you want to convert a single ASCII digit to its corresponding integer, you just need to subtract '0'. For example:

char digit = '7';
int num = digit - '0'; /* num is now 7 */

Edit:

Also, on my system, with the compiler I'm using, this code will print "Hello, world!". (But the results may be different for different compilers.)

#include <cstdio>

int main()
{
	char a = '\0', b = '!', c = 'd', d = 'l', e = 'r', f = 'o',
		g = 'w', h = ' ', i = ',', j = 'o', k = 'l', l = 'l', 
		m = 'e', n = 'H';

	puts(& n);


}

Rashakil Fol's last variation, using the subtraction of an ASCII '0', is the one I'd use.

And I've no clue what the last bit of code was, RF. That's stwange.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.