烫烫烫烫烫烫烫烫烫烫?C语言求解小问题
程序1:
- C/C++ code
# include <stdio.h>int main(void){ char str1[20],str2[20]; scanf("str1==%s",str1); printf("%s\n",str1); scanf("%s",str2); printf("str2==%s\n",str2); return 0;}===================
输入:
hello world
==============
输出:
=======
hello world
烫烫烫烫烫烫烫烫烫烫?
str2==hello
Press any key to continue
===========
程序2:
- C/C++ code
# include <stdio.h>int main(void){ char str1[20],str2[20]; scanf("%s",str1); printf("%s\n",str1); scanf("%s",str2); printf("str2==%s\n",str2); return 0;}输入:
===========
hello world
===========
输出:
=======
hello world
hello
str2==world
Press any key to continue
===========
求解?
[解决办法]
1.你scanf("str1==%s",str1)读入hello出错,因为hello不匹配str1==%s,而str1未初始化。所以会输出乱码
2.scanf("%s",str1);中%s遇到空白符停止,故两句scanf("%s",str1);会分别读出hello和world
[解决办法]
测试了一下你的程序,这个问题是scanf();的问题。你的写法是:scanf("str1==%s",str1);那么你的输入也需是:str1==helloworld。这样就不会有问题了。所以你在scanf();输入时,第一个参数中尽量不要加入像'\n',' '等这些字符,如果加了你在输入时必须要加,但是如果你加了'\n',即使你在最后也加了也不行。你的scanf();第一参数是str1==%s那么,那也要加上str1==.这也算是scanf函数的一个陷阱吧。
[解决办法]
++1
[解决办法]
fgets(str1,20,stdin);
if ('\n'==str1[strlen(str1)-1]) str1[strlen(str1)-1]=0;