首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 操作系统 > UNIXLINUX >

不知为什么不相等解决方案

2012-02-25 
不知为什么不相等#include stdio.h#include stdlib.hmain(){charbuf[50]intnumbuf1fgets(buf,50,st

不知为什么不相等
#include <stdio.h>
#include <stdlib.h>
main()
{
                char   buf[50];
                int   num;
                buf1=fgets(buf,50,stdin);   //stdin为标准输入
        printf( "%s ",buf1);       //从键盘输入buf1为xyz          
              if(strcmp(buf1, "xyz ")==0)
                    printf( "is   xyz ");
              else
                  printf( "is   not   xyz ");
         
}
可得到的buf1和“xyz”不相等。请朋友们给予指点!

[解决办法]
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char buf[50];
char *buf1;

buf1=fgets(buf,50,stdin); //stdin为标准输入
printf( "%s ",buf1); //从键盘输入buf1为xyz
if(strcmp(buf1, "xyz\n ")==0)
printf( "is xyz\n ");
else
printf( "is not xyz\n ");
return 0;
}
fgets reads characters from the current stream position to and including the first newline character, to the end of the stream, or until the number of characters read is equal to n–1.
[解决办法]
楼上正解: fgets会包括尾部的一个\n ,并在尾部添加一个\0...

[解决办法]
right

热点排行