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 << " ";
}
}