user2760309
user2760309

Reputation: 73

Quitting with Q

newcomer to C here. I seem to have run afoul on a problem that I have to do. The goal here is to make a program that writes out a two-digit number in words. Alternatively, the user can enter "Q" to quit. This is the bit that I am having trouble with. Can anyone point out what I am doing wrong?

#include <stdio.h>
int main(void)
{
int digit_one;
int digit_two;
enum state {fail, quit};
int status = fail;

printf("Enter a two-digit number or press Q to quit: ");
scanf("%1d%1d",&digit_one,&digit_two);

if(digit_one == 'Q'){
status = quit;
}
else {
if (digit_one == 1) {
    switch(digit_two % 10) {
        case 0: printf("You entered: Ten"); break;
        case 1: printf("You entered: Eleven"); break;
        case 2: printf("You entered: Twelve"); break;
        case 3: printf("You entered: Thirteen"); break;
        case 4: printf("You entered: Fourteen"); break;
        case 5: printf("You entered: Fifteen"); break;
        case 6: printf("You entered: Sixteen"); break;
        case 7: printf("You entered: Seventeen"); break;
        case 8: printf("You entered: Eighteen"); break;
        case 9: printf("You entered: Ninteen"); break;
    }
    return 0;
}

switch(digit_one % 10) {

    case 2: printf("You entered: Twenty-"); break;
    case 3: printf("You entered: Thirty-"); break;
    case 4: printf("You entered: Forty-"); break;
    case 5: printf("You entered: Fifty-"); break;
    case 6: printf("You entered: Sixty-"); break;
    case 7: printf("You entered: Seventy-"); break;
    case 8: printf("You entered: Eighty-"); break;
    case 9: printf("You entered: Ninety-"); break;
}
switch(digit_two % 10) {
    case 0: break;
    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;
}
return 0;
}
}

Upvotes: 0

Views: 127

Answers (2)

user694733
user694733

Reputation: 16033

Problem is that your scanf reads a string and converts it to integer immediately (thats what %d does).

You need to first read only a string (with %s or similar) to a buffer and then check that it is not 'Q'. After that you can do the conversion to integer with sscanf.

See http://en.cppreference.com/w/c/io/fscanf

Edit: Also, your code completely ignores the quit status.

Upvotes: 0

NPE
NPE

Reputation: 500167

You can't read Q into an integer variable. Read the input into a character one.

Upvotes: 3

Related Questions