0

Why is this program not working ... Can any one help ?

// program to accept digits of a number and display the number as one. #include<iostream> using namespace std; int main() { char t[100],a; int m=0; cout<<"Enter(press * after the last digit to stop entering.): "; while(a!='*') { cin>>a; t[m]=a; m++; } int c; c=t[0]*100+t[1]*10+t[2]; cout<<c; }

15th Apr 2018, 9:30 AM
Mr Doom
10 Answers
+ 3
I guess you already know cin >> intVar, or cin >> stringVar and use stoi() to convert string to integer, then I assume you must have a reason to get input that way, can you explain that?
15th Apr 2018, 10:12 AM
Ipang
+ 1
If you check out the ascii table https://www.asciitable.com/ You'll see that the numbers are in the range 48 - 57. If the user enters a 3 for example, what is actually stored is 51 If the user enters 345 51 52 53 is stored. t[0]*100+t[1]*10+t[2]; You are using those numbers here to do the math 51 * 100 + 52 * 10 + 53 = 5673 You'll have to convert those numbers to the correct value by subtracting '0', which equals 48 from these numbers (t[0]-'0')*100 + (t[1]-'0')*10 + (t[2]-'0'); (51 - 48)*100 + (52 - 48) * 10 + (53 - 48) = (3 * 100) + (4 * 10) + (5) = 345 Also a is uninitialized, in the event that a starts out with a '*' the loop isn't even entered. I recommend replacing the while loop with a do while loop instead or initializing a with anything besides '*'
15th Apr 2018, 10:26 AM
Dennis
Dennis - avatar
0
Well, it would help If you tell us what excatly error message do you get or what does not work.
15th Apr 2018, 9:34 AM
Mikuláš Suchanovský
Mikuláš Suchanovský - avatar
0
Their is no error it just won't work correctly.
15th Apr 2018, 9:35 AM
Mr Doom
0
I'm not sure what the program does do (I did read the description on top). What I would probbably do is use Switch and Cases instead of while(a!="*"). So it would look like: switch(a) { case('*') cin>>a; t[m] = a; m++; break; } You can check my code and scroll down for some examples: https://code.sololearn.com/cyqTln6peslH/?ref=app
15th Apr 2018, 9:44 AM
Mikuláš Suchanovský
Mikuláš Suchanovský - avatar
0
Ok thanks
15th Apr 2018, 9:50 AM
Mr Doom
0
I guess the main problem is that t is a char and c is a int, then the line c=t[0]*100+t[1]*10+t[2]; will give a weird result. You can solve it by declaring t as int, and then in the loop change the line t[m]=a; to t[m]=(int) a;
15th Apr 2018, 10:19 AM
Milonesa
0
But even though I use the do while loop I must set a condition by which the loop may exit.
15th Apr 2018, 11:15 AM
Mr Doom
0
Which you can do ? do { cin>>a; t[m]=a; m++; }while(a!='*');
15th Apr 2018, 11:19 AM
Dennis
Dennis - avatar
0
Thanks dude. I agree.
15th Apr 2018, 11:21 AM
Mr Doom