scanf 和 printf的奇怪问题

zzzkkk666 2008-04-03 09:58:19
printf的奇怪问题,输出时只有%s没有变量,居然没有出错。
怀疑是将最后一个scanf输入的内容缓存在某处,后面紧跟的输出语句直接输出了
不知原理是什么,

#include "string.h"
int main()
{
char temp33[10];
char temp[10];

int num=0,i=0;

printf("the input is === %s \n");//这里没输出
memset(temp, 0, sizeof(temp));

//printf("the input is === %s \n"); //这行打开会出错
printf("please input a word ");
scanf("%s",temp33);fflush(NULL);
scanf("%s", temp);
printf("-----------------------------------\n");
//printf("the input is === %s \n", temp);
printf("the input is === %s \n");fflush(NULL); //这里输出了temp2
printf("the input is === %s \n");fflush(NULL); //这里输出了temp2
for(i=0;i<10;i++)
{
printf("temp[%d] === [%c]\n", i, temp[i]);
}
//printf("the input is ===== %s \n"); //这里打开也出错
}

输入和输出结果如下
the input is ===
please input a word asdff
ggggg
-----------------------------------
the input is === ggggg
the input is === ggggg
temp[0] === [g]
temp[1] === [g]
temp[2] === [g]
temp[3] === [g]
temp[4] === [g]
temp[5] === []
temp[6] === []
temp[7] === []
temp[8] === []
temp[9] === []
...全文
121 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
sheenl 2008-04-03
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 sheenl 的回复:]
程序写错了, 没什么值得研究的东西.
典型的printf不安全的地方, printf不检查后面的可变数目的参数, 直接到栈上去取地址. 不管取来的是不是垃圾数据都照常处理.
[/Quote]

预防的方法就是, 在用printf, scanf这样不检查参数合法性的程序中, 自己小心的检查每一个参数是否正确. 因为编译器不会帮你检查.
zzzkkk666 2008-04-03
  • 打赏
  • 举报
回复
主要测试一下这种写错的情况为何会运行正常,以便预防之。
fflush(NULL);是将缓存中的内容都刷出来
运行环境是UNIX
myullian 2008-04-03
  • 打赏
  • 举报
回复
我用的vc++6.0,运行结果和楼主不一样啊
始终输出:the input is === @
打开第二个printf("the input is === %s \n")时也没有错误啊
输入输出不是一个缓冲区吧
If there are more arguments than there are format specifications, the extra arguments are ignored.
The results are undefined if there are not enough arguments for all the format specifications.
函数也没有返回值啊,return 0?
lanmuyi 2008-04-03
  • 打赏
  • 举报
回复
程序的目的是测试什么? 按正常的用法使用printf就可以了啊~
还有 fflush(NULL); 是要干什么?
cn34l 2008-04-03
  • 打赏
  • 举报
回复
你自己写的程序吗?可能是我学的太浅了,没看懂是什么意思~
memset将temp的所有元素都置为了NULL
fflush();这个也不明白..在是不是截取的代码?
fflush(NULL)是将所有打开的文件更新
printf();这个就不太了解了,如果你重新做一下会不会出错?
尝试将两个scanf中间的fflush去掉会怎么样?
sheenl 2008-04-03
  • 打赏
  • 举报
回复
程序写错了, 没什么值得研究的东西.
典型的printf不安全的地方, printf不检查后面的可变数目的参数, 直接到栈上去取地址. 不管取来的是不是垃圾数据都照常处理.
zzzkkk666 2008-04-03
  • 打赏
  • 举报
回复
多谢,培养自己仔细的习惯

69,369

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧