退出Q.

时间:2013-09-24 08:22:37

标签: c

这里是C的新人。 我似乎与我必须要做的问题发生冲突。这里的目标是制作一个用单词写出两位数字的程序。或者,用户可以输入“Q”退出。这是我遇到麻烦的一点。谁能指出我做错了什么?

#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;
}
}

2 个答案:

答案 0 :(得分:3)

您无法将Q读入整数变量。将输入读入一个字符。

答案 1 :(得分:0)

问题是,您的scanf读取字符串并且会立即将其转换为整数(这就是%d所做的事情。)

您需要先读取一个字符串(带有%s或类似字符串)到缓冲区,然后检查它是否为'Q'。之后,您可以使用sscanf转换为整数。

请参阅http://en.cppreference.com/w/c/io/fscanf

修改:此外,您的代码完全忽略了退出状态。