number to word code help-not for beginner apparently

I wasn't sure if this was best suited for general or for beginner.

Hello, the purpose of this program is to have a user input a number, and the program will then read out the number in words. Example: User inputs 10004, you get one zero zero zero four.

Also, any leading zero should be ignored. user inputs 00001, you get one.

Looking at the final for loop with the switch statement, part of my problem from setting up how the loop and the switch statement interact.

Any hints or ideas?

---------------

#include <stdio.h>

int main(){

int n,m,i,j,k,temp,temp2,numdigits; //add all the variables!

printf("Enter an integer no bigger than 10 digits and not starting with 0: ");//The only easy part of this program
scanf("%d",&n);

numdigits=0; //begin the count here
m=n;
for(j=0;m>0;j++)//counting the number of digits
{
m=m/10;//Divide m, initilized as n, by 10. Keep going until m<=0
numdigits=j+1;//numdigits: adds one to the count each time the loop runs.
}
HERE IS WHERE THE PROBLEM BEGINS
m=n;//re-initialize m as n
for (i=numdigits-1;i>=0;i--)
{
temp=0;
for (k=numdigits-1;k>=0;k--)
{
temp=temp*10;
temp2=n%10;
temp=temp+temp2;
m=temp2%10;
}


switch (m){
case 1:
printf("one ");
break;
case 2:
printf("two ");
break;
case 3:
printf("three ");
break;
case 4:
printf("four ");
break;
case 5:
printf("five ");
break;
case 6:
printf("six ");
break;
case 7:
printf("seven ");
break;
case 8:
printf("eight ");
break;
case 9:
printf("nine ");
break;
case 0:
printf("zero ");
default:
printf("error!");
}
}
return 0;
}
Last edited on
Please use codetags: http://www.cplusplus.com/articles/jEywvCM9/

One of your problems is that case '0' is lacking a break

After HERE IS WHERE THE PROBLEM BEGINS you assign m a value. Then you assign temp the value 0. You then manipulate the value you assigned to temp and ultimately assign 0 to m. You should be manipulating the value in m, not the 0 in temp.

A recursive solution:
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
#include <stdio.h>
#include <stdlib.h>

void print(int n)
{
    static const char* digit_rep [] =
    {
        "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"
    };

    if (n)
    {
        print(n / 10);
        printf("%s ", digit_rep[abs(n%10)]);
    }
}

int main()
{
    int n;
    printf("Enter an integer: ");
    scanf("%d", &n);

    if (n)
        print(n);
    else
        printf("zero\n");
}
Last edited on
Topic archived. No new replies allowed.