首页 > 解决方案 > if 语句不接受 strcmp 字符串输入中的输入

问题描述

#include <stdio.h>
#include <conio.h>
#include <string.h>

main() {
    char d[10];
    int value = 0, val1, val2;
    printf("Enter Day: ");
    scanf("%c", &d);

    val1 = strcmp(d, "sunday");
    val2 = strcmp(d, "saturday");
    
    if (val1 == 0) {
        printf("AS");
        value = 2;  
    } else
    if (val2 == 0) {
        value = 1;   
    } 
       
    switch (value) {
      case 2:
        printf("So sad, you will have to work");
        break;
      case 1:
        printf("Enjoy! its holiday");
        break;
      default:
        printf("Print valid character");
    }
}

我在这里输入代码想要输入天数并使用switch语句获得一些输出但strcmp在语句中不起作用if我必须使用switch语句也 if语句不识别值。

标签: ccomparisonstrcmp

解决方案


至少这个问题:

strcmp(d,"sunday")期望数组d包含一个字符串

d肯定不包含字符串,因为那里没有分配空字符。

char d[10];
printf("Enter Day: ");
scanf("%c",&d);  // Writes, at most, 1 character to `d`. Remainder of `d[]` is uninitialized.

反而

if (scanf("%9s",d) == 1) {
  printf("Success, read <%s>\n", d);

提示:考虑使用fgets()来读取用户输入。

提示:启用所有编译器警告以节省时间。


推荐阅读