【问题标题】:if statement not taking input in strcmp string inputif 语句不接受 strcmp 字符串输入中的输入
【发布时间】:2020-12-17 07:22:53
【问题描述】:
#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 语句获得一些输出,但strcmpif 语句中不起作用 我还必须使用switch 声明 if 声明不承认价值。

【问题讨论】:

  • 符号main() { … } 在整个千年中一直是非标准的;它在 C99 中是非标准的。您不应该编写过时的代码!您应该明确指定返回类型 (int),当您的程序不注意命令行参数时,最好使用 int main(void)
  • 显示的代码没有使用&lt;conio.h&gt; AFAICS 的任何功能;省略标题。您应该在default: 案例之后包含break;,以防止未来的增强。您应该在各种 printf() 语句的末尾输出一个换行符——养成用换行符终止输出的习惯。
  • 错误:scanf("%c",&amp;d);。应该是%s。投票结束是一个简单的错字。
  • 你把 strcmp 弄得太复杂了。您不需要额外的开关。这使得代码更难阅读。

标签: c comparison strcmp


【解决方案1】:

至少这个问题:

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() 来读取用户输入。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-09
    • 1970-01-01
    • 2015-09-20
    • 1970-01-01
    • 2014-02-25
    相关资源
    最近更新 更多