为什么 C 中的 if 过程不适用于 char

And*_*rew -2 c if-statement char

我正在用 C 编写一个简单的测验(使用 CodeBlocks 13.12)

它可以编译,但在第二个问题中不起作用。无论我输入什么,它总是给出答案“这很伤心”。我不明白出了什么问题。我来到这里,如果我注释第 13 行(scanf("%d", &age);),那么第二个问题就可以正常工作了。问题是什么?

#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;
}
Run Code Online (Sandbox Code Playgroud)

cad*_*luk 5

您通过以下方式导致未定义的行为

scanf("%c%c", &S1);
Run Code Online (Sandbox Code Playgroud)

scanf读取两个 chars,一个存储在 中S1,一个存储在堆栈上的某个位置,因为scanf期望提供第二个。 char*

如果您的目的是忽略实际字符后面的换行符,请写

scanf("%c%*c", &S1);
Run Code Online (Sandbox Code Playgroud)