having trouble using ch[]
Oct 27, 2013 at 1:11am UTC
I came up with this code to try to add each number from a zip code inputted by the user but I think I'm adding up the ascii values not the real values the user is inputting. How I can go from ascii to the real digit. This is my code so far
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
#include <iostream>
#include <iomanip>
#include <string>
#include <conio.h>
using namespace std;
int main()
{
int total = 0;
char ch[5];
cout << "Please input your 5 digit zip code: " ;
for (int i=0; i<5; i++)
{
ch[i] = getch();
total = total + ch[i];
cout << ch[i];
}
cout << endl;
cout << total << endl;
return 0;
}
Oct 27, 2013 at 1:19am UTC
cout << "Please input your 5 digit zip code: ";
You want to input ascii values?
1 2 3 4 5 6 7 8 9
int temp;
for (int i=0; i<5; i++)
{
cin >> temp;
ch[i] = temp;
total = total + ch[i];
cout << ch[i];
}
Last edited on Oct 27, 2013 at 1:27am UTC
Oct 27, 2013 at 1:29am UTC
no I want the user to input something like 92010 and add all those numbers up and make up a bar code like the mailing system
Oct 27, 2013 at 1:38am UTC
Oh, sorry. Is it what you need?
1 2 3 4 5
for (int i=0; i<5; i++)
{
ch[i] = getche(); // It's equivalent to cout<< (char)getch();
total = total + (ch[i] - '0' ); // real digit value
}
Oct 27, 2013 at 1:44am UTC
Yes that's perfect man! thank you so much. but I just have one more question. why do you subtract ch[i] from 0.
Topic archived. No new replies allowed.