c - 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
语句不识别值。
解决方案
至少这个问题:
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()
来读取用户输入。
提示:启用所有编译器警告以节省时间。
推荐阅读
- java - 预期 BEGIN_ARRAY 但 BEGIN_OBJECT Retrofit Api 调用失败
- spring-boot - Spring boot devtools和依赖的spring项目
- javascript - 后台应用程序,带 setTimeout 和推送通知
- javascript - Three.js - 自定义网格上的奇怪线条
- perl - 如何在 perl 单行中回到文件的开头?
- api - Quip 是否有文档搜索 API?
- tensorflow - 加载/应用 TFX Beam 变换图时 TFX 变换等级不匹配
- marklogic - MarkLogic - 自定义休息 GET REST 服务的性能变化
- angular - 使用 URL 中的参数发送 Post 请求
- robotframework - 预计至少有 1 个参数,得到 0