问一个容易搞糊涂的有关问题
问一个容易搞糊涂的问题?
题目:从键盘读数据写入文件test中,再读出显示。
#include "stdio.h "
#include "stdlib.h "
#include "io.h "
int main()
{
FILE *fp;
char s[80];
int t;
if((fp=fopen( "test ", "w "))==NULL)
{
printf( "cannot open this file\n ");
exit(1);
}
printf( "Enter a string and a number: ");
fscanf(stdin, "%s%d ",s,&t);
fprintf(fp, "%s%d ",s,t);
fclose(fp);
if((fp=fopen( "test ", "r "))==NULL)
{
printf( "cannot open this file\n ");
exit(1);
}
fscanf(fp, "%s%d ",s,&t);
fprintf(stdout, "%s%d ",s,t);
return 0;
}
问:(1)为什么我输入:abcfdj 3 输出结果是:abcfdj33
这多出的一个3是哪里来的?????
(2)在上题fscanf和fprintf中fp和stdin或者fp和stdout是否可以相互代替的?用stdin或fp有什么区别?用stdout或fp有什么区别?
------解决方案--------------------
%s格式输入字符串的时候遇到空格表示输入结束了.
按道理你结果应该是abcfdj3才对啊...
(2)用fscanf时,fp表示从文件格式化输入.stdin表示从键盘格式化输入.
fprintf时,fp表示在文件中显示,stdout表示在屏幕上显示.
题目:从键盘读数据写入文件test中,再读出显示。
#include "stdio.h "
#include "stdlib.h "
#include "io.h "
int main()
{
FILE *fp;
char s[80];
int t;
if((fp=fopen( "test ", "w "))==NULL)
{
printf( "cannot open this file\n ");
exit(1);
}
printf( "Enter a string and a number: ");
fscanf(stdin, "%s%d ",s,&t);
fprintf(fp, "%s%d ",s,t);
fclose(fp);
if((fp=fopen( "test ", "r "))==NULL)
{
printf( "cannot open this file\n ");
exit(1);
}
fscanf(fp, "%s%d ",s,&t);
fprintf(stdout, "%s%d ",s,t);
return 0;
}
问:(1)为什么我输入:abcfdj 3 输出结果是:abcfdj33
这多出的一个3是哪里来的?????
(2)在上题fscanf和fprintf中fp和stdin或者fp和stdout是否可以相互代替的?用stdin或fp有什么区别?用stdout或fp有什么区别?
------解决方案--------------------
%s格式输入字符串的时候遇到空格表示输入结束了.
按道理你结果应该是abcfdj3才对啊...
(2)用fscanf时,fp表示从文件格式化输入.stdin表示从键盘格式化输入.
fprintf时,fp表示在文件中显示,stdout表示在屏幕上显示.