简体   繁体   English

为什么程序如果在 C 中不适用于 char

[英]Why procedure if in C doesn't work with char

I am writing a simple quiz in C (using CodeBlocks 13.12)我正在用 C 编写一个简单的测验(使用 CodeBlocks 13.12)

It compiles, but doesn't work in second question.它编译,但在第二个问题中不起作用。 Whatever I will input, it always give answer ' that's sad '.无论我要输入什么,它总是给出'那很悲伤'的答案。 I can't understand what is wrong.我不明白出了什么问题。 I came to this, where if I comment line 13 ( scanf("%d", &age); ) it's starting works ok for second question.我来到了这里,如果我评论第 13 行( scanf("%d", &age); ),它开始可以用于第二个问题。 What the problem is?问题是什么?

#include <iostream>
#include <stdio.h>
#include <windows.h>
#include <clocale>


int main()
{

int age;
char S1;

printf("How old is your dog? \n");
scanf("%d", &age);

if (age <= 7)
    {
        printf(" very young. the end \n");
        return 0;
    }
else
    {
        printf("old dog. \n \n");
    }

//question2

printf("Do you like dogs? y/n \n");
scanf("%c%c", &S1);

if (S1 == 'y')
    {
         printf("hey, that's nice \n");
    }
else
    {
        printf(" that's sad :( . \n");
        return 0;
    }
 return 0;
}

You cause undefined behavior by你导致未定义的行为

scanf("%c%c", &S1);

scanf reads two char s, one stored in S1 , one stored in some location on the stack because scanf expects a second char* to be supplied. scanf读取两个char ,一个存储在S1 ,一个存储在堆栈上的某个位置,因为scanf期望提供第二个char*

If your intention is to ignore the newline following the actual character, write如果您打算忽略实际字符后面的换行符,请写

scanf("%c%*c", &S1);

Change the second scanf() to将第二个scanf()更改为

scanf(" %c", &S1);

This would escape the left out newline character \\n in the input buffer.这将转义输入缓冲区中遗漏的换行符\\n

Plus, you are reading one char in this.另外,您正在阅读其中的一个char So you need only one %c所以你只需要一个%c

scanf("%c", &S1);

是输入一个字符的正确方法,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM