3

scanf 字符有问题...运行程序时不要让我输入字符 当我输入整数时程序会打印 printf 并转到最后一个 else ...

#include <stdio.h>
#include <stdlib.h>

#define EG 0.23
#define AG 0.70
#define TG 0.15

main() {
    int posothta;
    char eidos;
    float poso;

    printf("Dwse posothta grammatosimwn: ");
    scanf("%d",&posothta);
    printf("Dwse to eidos grammatoshmou: ");
    scanf("%c",&eidos);

    if(eidos=='E' || eidos=='e'){
        poso=posothta*EG;
        printf("To poso pou plirwnoume einai: %f",poso);
    }else if(eidos=='A' || eidos=='a'){
        poso=posothta*AG;
        printf("To poso pou plirwnoume einai: %f",poso);
    }else if(eidos=='T' || eidos=='t'){
        poso=posothta*TG;
        printf("To poso pou plirwnoume einai: %f",poso);
    }else{
        printf("Kapou exei gine kapoio la9os");
    }   

    return 0;
}
4

2 回答 2

4

When you do a scanf() it's taking the value you ask for only.. for example:

scanf("%d",&posothta);

Let's say I enter 5 here. Really, stdin got 2 characters: '5' and '\n' (because I had to hit the enter key and that generates a newline character).

So into posothta goes the 5, but that pesky newline is left sitting there. The next scanf() now is looking for a character, and since the newline character ('\n') is indeed a character, the program doesn't ask questions, it simply picks up that newline and moves on.

Change your code to:

scanf(" %c",&eidos);

Will skip tell scanf() that "I want you to skip any whitespace characters, then grab the next one". To scanf() a white space character includes not only spaces, but newlines as well.

于 2013-03-04T18:37:06.610 回答
0

您需要刷新缓冲区:

printf("Dwse posothta grammatosimwn: ");
scanf("%d",&posothta);
flushall();
printf("Dwse to eidos grammatoshmou: ");
scanf("%c",&eidos);

flushall() 函数:

#include <stdio.h>
int flushall( void );

描述:

flushall() 函数清除与输入流关联的所有缓冲区,并写入与输出流关联的所有缓冲区。对输入文件的后续读取操作会导致从相关文件或设备中读取新数据。

调用 flushall() 函数相当于对所有打开的流文件调用 fflush()。

回报:

打开的流的数量。当写入文件时发生输出错误时,将设置全局变量 errno。

于 2013-03-04T18:45:42.907 回答