Check this typecasting in C++

63 views Asked by At

Help me in correcting this. I want the answer as 123 only, but it shows some insane outputs.

#include<iostream>
#include<stack>
#include<string.h>
using namespace std;
int main()
{
    char a[] = "123 234 435 - ";
    int i = 0;
    int b[100];
    int j = 0;
    while (a[i] != ' ')
    {
        b[j] = a[i] - '0';
        j++;
        i++;
        //  cout<<b[j]<<endl;
    }
    for (int k = 0; k<j; k++)
    {
        cout << b[j];
    }
}
2

There are 2 answers

0
marom On

The notes as comments below

// initialization of b[0] is required
while (a[i] != ' ')
{
    b[j] = a[i] - '0'; // what about higher digits? a 10*b[i] is missing
    j++; // why? b[0] is not over yet
    i++;
    //  cout<<b[j]<<endl;
}
0
cruxion effux On

Insane outputs ?

You are doing :

b[j] = a[i] - '0'

a[i] when i = 0 is 1 so ascii of 1(49)- ascii of 0(48) = 1 so the character corresponding of ascii goes into b[j](and similarly for others i and j values) and thus you get some confusing characters and not 123 , for 123 you just need to put b[j] = a[i] .

Also note that in the printing loop you should have cout << b[k].