C++中scanf的怪异行为 [英] Weird behaiviour of scanf in C

查看:26
本文介绍了C++中scanf的怪异行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

if (a % 5) {
    goto ask;
}
else {
    goto main;
}

ask:
printf("Do You Want To Exit ? Y \ N . . . 
");
scanf("%c", &YN);
getch();
if (YN == 'Y') {
y:
    system("cls");
    YN = 1;
    goto sign;
}
else if (YN == 'y') {
    goto y;
}
else if (YN == 'N') {
n:
    system("cls");
    YN = 0;
    goto sign;
}
else if (YN == 'n') {
    goto n;
}
else {
    printf("Sorry ..Didn't Catch that ... ");
    goto ask;
}

有人能帮我了解一下出了什么问题吗? 出于某种原因,我从这段代码中得到的输出是 是否要退出(&Q;D) ?&报价; 加查尔..。 对不起,没听清您想退出吗? ?

看起来像是第一次跳过scanf(),程序直接转到else==&>"sorry i didnt get that" 并且只在第二次解决了如何使用scanf()

推荐答案

scanf()使用%c读取字符,是的,%c[检查下面的扰流器]按%cEnter键非常有效。

Enter键==换行符

使用

scanf(" %c", &YN);  //mind the space brefore `%c`
       ^
       |

忽略以前存储的任何[也是前导]空格[包括换行符。]

注意:这样还不需要getch();

这篇关于C++中scanf的怪异行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆