为什么代码只输出 'Have a nice day?' 尽管输入了 Friday 并声明了给定的字符串?
Why does the code output only 'Have a nice day?' In spite of inputting Friday and declaring the given string?
我正在编写一个 c 程序,如果当天是星期五,则使用 if-else 语句打印特定语句。涉及什么错误?
我试过对同一代码使用整数值并且它有效,但是当我将 n 等同于星期五时,输出仅显示其他部分。
char s[10]="Friday";
char n[6];
printf("Enter a day:\n");
scanf("%s",n); //n is string
if(n==s)
printf("Have a nice weekend!");
else
printf("Have a nice day!");
我希望 "Friday" 的输出为 "Have a nice weekend!",但任何输入的输出都是 "Have a nice day!"。
您应该使用类似 strcmp 的函数来比较 C
中的字符数组。
if(strcmp(s, n) == 0) {
printf("Have a nice weekend!");
}
当您使用 ==
运算符时,您比较的是地址(有时是指针),而不是字符串文字值。
同样如上所述(双关语)C
中的数组需要 space 作为空终止字符。
对于初学者,您应该扩大数组,因为字符串文字 "Friday"
无法放入数组。
例如
char n[10];
其次,使用标准函数 fgets
而不是 scanf
,因为 scanf
在您的程序中编写是不安全的。
例如
fgets( n, sizeof( n ), stdin );
您可以通过以下方式删除尾随换行符
n[ strcspn( n, "\n" ) ] = '[=12=]';
为此,您必须包含 header <string.h>
。
在此声明中
if(n==s)
有字符串首字符的比较地址。您需要使用标准字符串函数 strcmp
来比较字符串本身而不是指针。例如
if ( strcmp( n, s ) == 0 )
这是一个演示程序
#include <stdio.h>
#include <string.h>
int main(void)
{
const char *s = "Friday";
char day[10];
printf( "Enter a day: " );
fgets( day, sizeof( day ), stdin );
day[ strcspn( day, "\n" ) ] = '[=15=]';
if ( strcmp( day, s ) == 0 )
{
printf( "Have a nice weekend!" );
}
else
{
printf( "Have a nice day!" );
}
return 0;
}
它的输出可能看起来像
Enter a day: Friday
Have a nice weekend!
我正在编写一个 c 程序,如果当天是星期五,则使用 if-else 语句打印特定语句。涉及什么错误?
我试过对同一代码使用整数值并且它有效,但是当我将 n 等同于星期五时,输出仅显示其他部分。
char s[10]="Friday";
char n[6];
printf("Enter a day:\n");
scanf("%s",n); //n is string
if(n==s)
printf("Have a nice weekend!");
else
printf("Have a nice day!");
我希望 "Friday" 的输出为 "Have a nice weekend!",但任何输入的输出都是 "Have a nice day!"。
您应该使用类似 strcmp 的函数来比较 C
中的字符数组。
if(strcmp(s, n) == 0) {
printf("Have a nice weekend!");
}
当您使用 ==
运算符时,您比较的是地址(有时是指针),而不是字符串文字值。
同样如上所述(双关语)C
中的数组需要 space 作为空终止字符。
对于初学者,您应该扩大数组,因为字符串文字 "Friday"
无法放入数组。
例如
char n[10];
其次,使用标准函数 fgets
而不是 scanf
,因为 scanf
在您的程序中编写是不安全的。
例如
fgets( n, sizeof( n ), stdin );
您可以通过以下方式删除尾随换行符
n[ strcspn( n, "\n" ) ] = '[=12=]';
为此,您必须包含 header <string.h>
。
在此声明中
if(n==s)
有字符串首字符的比较地址。您需要使用标准字符串函数 strcmp
来比较字符串本身而不是指针。例如
if ( strcmp( n, s ) == 0 )
这是一个演示程序
#include <stdio.h>
#include <string.h>
int main(void)
{
const char *s = "Friday";
char day[10];
printf( "Enter a day: " );
fgets( day, sizeof( day ), stdin );
day[ strcspn( day, "\n" ) ] = '[=15=]';
if ( strcmp( day, s ) == 0 )
{
printf( "Have a nice weekend!" );
}
else
{
printf( "Have a nice day!" );
}
return 0;
}
它的输出可能看起来像
Enter a day: Friday
Have a nice weekend!