For this project, you will simulate this conversion. Your program will ask the user to enter a 4 digit numerical value. As the programmer, you will input the value as a string. You will devise an algorithm to convert the string of characters (string of digits) to a single integer, stored in a single integer value. At the end of this algorithm, you will print the addition (using the + operator) of the input string to itself, and the addition of the converted integer to itself. For example, if the user were to input 9275, the outputs would be 18550 and 92759275.Your program should generate appropriate error messages if the user enters: (1) less than 4 digits, (2) more than 4 digits, or (3) any non-numeric digits.
I came up with the code below and there are a couple of errors, can someone help me out? TIA
After running the program for awhile I noticed this:
1 2 3 4 5 6 7 8 9
for (int k = 0; k<len; k++)
if (num[i]<48 || num[i]>57)
// <--- Could use a pause here to allow the user to read the display before exit.
Do you see any problem between the loop iterator and the subscript?
Also this would work better: if (num[i] < '0' || num[i] > '9'). This way you do not nee to remember or look up the decimal value of zero - nine.
Lines 26 - 29 should come after the input to check the length. I used an if/else if to print a different message depending on the length.
The for loop at line 23 could easily be achieved withdec = atoi(num);.
One last point to keep in mind. Since you want to do a "strcat" of "num" into "num", "num" will need to be a multiple of 4 + 1 for the '\0' at the end and "num" will need to be large enough to hold a number greater than 4 when you first input a number.