简体   繁体   English

C-if / else语句

[英]C - if/else statement

I'm fairly competent with if/else statements, and this is a really old assignment that I ended up turning in partially complete. 我对if / else语句相当称职,这是一个非常古老的任务,我最终完成了部分工作。 But I still wanted to know exactly why my code wouldn't work. 但是我仍然想确切地知道为什么我的代码不起作用。

I want my user to input name, height, and sex. 我希望用户输入姓名,身高和性别。 My code will then display an entire sentence that says "Name is X cm tall and is a male" or "Name is X cm tall and is a female." 然后,我的代码将显示一个完整的句子,上面写着“姓名高X厘米,是男性”或“姓名高X厘米,是女性”。

When I input name and enter, it immediately then skips displays both the height AND the sex. 当我输入姓名并输入时,它会立即跳过,同时显示身高和性别。 Regardless of what I input after that, it then ends the program. 无论我在此之后输入什么,它都将结束程序。

Input name: Jack Input height in cm: 180 sex(M/F): Computer $ 输入名称:杰克输入身高(厘米):180性别(男/女):电脑$

I've been playing around with this code for a while now, but I have been stuck for a while now. 我已经在这段代码中玩了一段时间了,但是我已经被卡住了一段时间了。 Any help would be greatly appreciated. 任何帮助将不胜感激。 Here is my code: 这是我的代码:

#include<stdio.h>

int main() {
  char name[30];
  char sex;
  float height; 

  printf("Input name: ");
  scanf("%s", name);
  fflush(stdin);
  printf("Input height in cm: ");
  scanf("%f", &height);
  fflush(stdin);

  printf("sex(M/F): ");
  scanf("%c", &sex);
  if (sex == 'M') 
  {
    printf("%s is %f cm tall and male", name, height);
  }
  else if (sex == 'F')
  {
    printf("%s is %f cm tall and female", name, height);
  }
  printf("\n");
  return 0;
}

From what I can see it only skips the sex part - which is very sad to be honest :-)). 从我可以看到它仅跳过性的部分 - 这是很可悲的是诚实的:-))。

it immediately then skips displays both the height AND the sex 它会立即跳过,同时显示身高和性别

Input name: Jack Input height in cm: 180 sex(M/F): Computer $ 输入名称:杰克输入身高(厘米):180性别(男/女):电脑$

You can try this: 您可以尝试以下方法:

scanf(" %c", &sex);
       ^

The space causes scanf to eat blanks before reading a character. 该空格使scanf在读取字符之前先吃掉空白。

fflush(stdin) is a very bad idea (undefined behavior). fflush(stdin)是一个非常糟糕的主意(未定义的行为)。 You should replace this call with an other function call, for example this one : 您应该将此调用替换为其他函数调用,例如:

static void
clean_stdin(void)
{
    int c;
    do {
        c = getchar();
    } while (c != '\n' && c != EOF);
}

With it, it seems working. 有了它,似乎工作。

You're missing an ampersand on line 9: 您在第9行缺少了一个&符:

scanf("%s", name);

shoul be: 应该是:

scanf("%s", &name);

maybe this helps 也许这有帮助

You can also try this 您也可以尝试

printf("sex(M/F): ");
scanf("%s", &sex);

要从标准输入中读取单个字符,您必须使用getchar()而不是scanf(“%c”,&c)或将sex的变量类型更改为char [2]并使用scanf(“%s”,sex)

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

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