Question

im storing a value, say 6 under a character array. i want to pass the same value 6 to an integet array but simply this code dosent work :

char a[3];
gets(a);              (for ex: value of a i.e a[0] is 6)
int b[3];
for(int i=0;i<strlen(a);i++)
b[i]=a[i];
cout<<b;               (it returns 54 nd not 6)

the above code stores the INTEGER VALUE of 6 in it. it does not store 6 directly. i want to store the same no 6 and not the integer value (i.e 54). any ideas?

thanks in advance

Was it helpful?

Solution

You are storing character codes, and not integers. If you type 1 on the standard input and store that in a char, what will get stored is the ASCII code for 1, and not the integer value 1.

Thus, when you assign that to b[i], you should do:

b[i] = a[i] - '0'; // Of course, this will make sense only as long
                   // as you provide digits in input.

Moreover, doing:

cout << b;

Will print the address of the b array, and not its content. Also, using strlen() here is not a great idea, because your array a is not null-terminated.

Letting aside the considerations on how type-unsafe this is, here is what you possibly meant to do:

#include <iostream>
#include <cstring>

using std::cout;

int main()
{
    char a[3] = { 0, 0, 0 };
    gets(a);

    int b[3];
    for(unsigned int i = 0; i < std::min(strlen(a), 3u); i++)
    {
        b[i] = a[i] - '0';
    //              ^^^^^
        cout << b[i];
    }
}

Here is how you would do the above in C++11:

#include <iostream>
#include <string>
#include <vector>

int main()
{
    std::string a;
    getline(std::cin, a);

    std::vector<int> b;
    for (char c : a) { if (std::isdigit(c)) b.push_back(c - '0'); }

    for (int x : b) { std::cout << x << " "; }
}

Here is a modification of the above function that should work for C++03 as well:

#include <iostream>
#include <string>
#include <vector>

int main()
{
    std::string a;
    getline(std::cin, a);

    std::vector<int> b;
    for (std::string::iterator i = a.begin(); i != a.end(); i++)
    {
        if (std::isdigit(*i)) b.push_back(*i - '0');
    }

    for (std::vector<int>::iterator i = b.begin(); i != b.end(); i++)
    {
        std::cout << *i << " ";
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top