简体   繁体   English

在C中读取File时输出错误

[英]Errorneous output while reading File in C

I am trying to write a string to a file and then read the string and output the string written into the file. 我正在尝试将字符串写入文件,然后读取该字符串并将输出的字符串写入文件。 For example 例如

INPUT (Input Name)
FalconHawk

OUTPUT
Hi FalconHawk! Have a great day!

My code is: 我的代码是:

#include<stdio.h>

void main(){

char n[10],r[1000];
FILE *fptr,*fpt;

scanf("%s",n);                        //Input name

fptr=fopen("welcome.txt","w");
fprintf(fptr,"%s",n);                 //Write to file
fclose(fptr);

fpt=fopen("welcome.txt","r");
fscanf(fpt,"%s",r);                 
printf("Hi %s! Have a good day.",r);  //Output file content
fclose(fpt);
}

But because of some reason I am getting an output like 但是由于某种原因,我得到的输出像

INPUT (Input Name)
FalconHawk

OUTPUT
HiHi FalconHawk! Have a great day!   //"Hi" is getting printed two times

On replacing "Hi" with "Welcome" I am getting an output like 用“ Welcome”替换“ Hi”时,我得到的输出是

OUTPUT
WelcomeWelcome FalconHawk! Have a great day!   //"Welcome" is getting printed two times.

What is causing this issue? 是什么导致此问题?

Your buffer is too small and there's no room for the terminating null byte, therefore, your code invokes undefined behavior. 您的缓冲区太小,终止null字节没有空间,因此,您的代码将调用未定义的行为。 If you want to read 10 characters, then this is how you should do it 如果您想读取10个字符,则应该这样做

char input[11];
if (scanf("%10s", input) == 1) {
    // Safely use `input' here
}

And if you want to read an entire line of text from stdin then use fgets() instead 如果您想从stdin中读取整行文本,请使用fgets()代替

if (fgets(input, sizeof input, stdin) != NULL) {
    // Safely use `input' here
}

Strings in c always need an extra byte of space to store the terminating '\\0' , read a basic tutorial on strings in c to learn how they work and how to treat them. c中的字符串始终需要额外的字节空间来存储终止符'\\0' ,请阅读有关c中的字符串的基本教程,以了解它们的工作方式和处理方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM