gpt4 book ai didi

c - 为什么 fprintf()/fscanf()/printf() 在我的 Dec-to-Binary 程序中显示错误的输出,而 printf() 和 sscanf() 工作正常?

转载 作者:行者123 更新时间:2023-11-30 18:32:07 27 4
gpt4 key购买 nike

我最初编写这个程序只是为了显示十进制整数的二进制形式,但我发现它很粗糙,因为它只是使用 prinf() 并排打印位。所以我使用sprintf() 将其写入字符串,当我使用 sscanf() 检索它并显示它时,它工作正常。

但是,如果我想使用 fprintf() 将结果写入文件,fprintf()/fscanf()/printf() 组合会出现一些难以理解的问题>,使用 fscanf() 检索它并在屏幕上显示它。它只是显示损坏的输出。奇怪的是,当我在记事本中打开文件时,它具有预期的二进制形式那里有整数。但它不会在屏幕上显示它。似乎是一个小问题,但我不知道是什么。我会很感激你的回答。

编辑您可以直接跳到rewind(fp)部分,因为问题可能出在其后的 3 行中。

#include<stdio.h>
#include<stdlib.h>

void bform(int);

int main()
{
int source;
printf("Enter the integer whose binary-form you want\n");
scanf("%d",&source);
printf("The binary-form of the number is :\n");
bform(source);
return 0;
}

void bform(int source)
{
int i,j,mask;
char output[33],foutput[33];
FILE *fp;
fp=fopen("D:\\final.txt","w");

if(fp==NULL)
{
printf("I/O Error");
exit(-1);
}

for(i=31; i>=0; i--)
{
mask=1;

//Loop to create mask
for(j=0; j<i; j++)
{
mask=mask*2;
}

if((source&mask)==mask)
{
sprintf(&output[31-i],"%c",'1');
printf("%c",'1');
fprintf(fp,"%s","1");
}
else
{
sprintf(&output[31-i],"%c",'0');
printf("%c",'0');
fprintf(fp,"%s","0");
}
}

printf("\nThe result through sprintf() is %s",output);
rewind(fp);
fscanf(fp,"%s",foutput);
printf("\nThe result through fprintf() is %s",foutput); //Wrong output.
fclose(fp);

}

输出:

Enter the integer whose binary-form you want  25
The binary-form of the number is :
00000000000000000000000000011001
The result through sprintf() is 00000000000000000000000000011001
The result through fprintf() is ÃwxÆwàþ#

最佳答案

因为您以只写访问方式打开文件。您无法读取它,并且您没有检查 fscanf 的返回值,因此您看不到它失败。

如果您还希望能够读回您所写的内容,请将模式“w”更改为“w+”

关于c - 为什么 fprintf()/fscanf()/printf() 在我的 Dec-to-Binary 程序中显示错误的输出,而 printf() 和 sscanf() 工作正常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16493583/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com