首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

新手请问scanf()自动跳过的有关问题

2012-10-13 
新手请教scanf()自动跳过的问题先上代码C/C++ code#include stdio.h#include stdlib.h#include math.

新手请教scanf()自动跳过的问题
先上代码

C/C++ code
#include "stdio.h"#include "stdlib.h"#include "math.h"double teacher_total(double _amount){    double total;    printf("Total purchases                                  $%6.2lf\n", _amount);    if(_amount >= 100)    {        total = _amount * (1 - 0.12);        printf("Teacher's discount (12%%)                            %6.2lf\n", _amount * 0.12);        printf("Discounted total                                  $%6.2lf\n", total);    }    else{        total = _amount * (1 - 0.10);        printf("Teacher's discount (10%%)                            %6.2lf\n", _amount * 0.10);        printf("Discounted total                                  $%6.2lf\n", total);    }    printf("Sales tax (5%%)                                       %6.2lf\n", total * 0.05);    printf("Total                                             $%6.2lf\n", total * 1.05);}double non_teacher(double _amount){    printf("Total purchases                                   $%6.2lf\n", _amount);    printf("Sales tax (5%%)                                       %6.2lf\n", _amount * 0.05);    printf("Total                                             $%6.2lf\n", _amount * 1.05);}int main(){    double amount;    char is_teacher;    printf("KEITH'S SHEET MUSIC CALCULATOR\n");    printf("Please enter the total amount for purchase ($):\n");    scanf("%lf", &amount);    printf("Are you a music teacher? ");    scanf("%c", &is_teacher);    printf("\n");    printf("RECEIPT\n");    if(is_teacher == 'Y')    {        teacher_total(amount);    }    else{        non_teacher(amount);    }    system("PAUSE");    return 0;    }

扫描is_teacher的那个scanf每次都跳过然后就运行else里面的non_teacher,不知道怎么回事。 把is_teacher换成int 'Y'变成1就没有问题。是我scanf里面的书写有问题吗?

[解决办法]
探讨

好吧我自己解决了把%c换成%s就好了o.0

[解决办法]
探讨

C/C++ code

#include "stdio.h"
#include "stdlib.h"
#include "math.h"

double teacher_total(double _amount)
{
double total;
printf("Total purchases $%6.2lf\n"……

[解决办法]
因为 %s 不读取空白字符 包括 制表符空格符回车符等等 
然后换成%s是不可取的 %s会多写入一个字符'\0' 但是你只提供了一个char
错误类似数组越界

"%c" 换成 " %c"注意有一个空格 就行了

热点排行