I am trying to read a file and store the contents of file into three different array using below code
我正在尝试读取文件并使用下面的代码将文件的内容存储到三个不同的数组中
#include<stdio.h>
# define max 10
int main()
{
char filename[10];
int at[max],n=0,i;
float bt[max];
char pno[max][2];
printf("Enter the file name :- ");
scanf("%s",filename);
FILE *fp=fopen(filename,"r");
while(fscanf(fp, "%s %d %f" ,pno[n],&at[n],&bt[n])!=EOF)
n++;
for(i=0;i<n;i++)
printf("%s\t%d\t%f\n",pno[i],at[i],bt[i]);
return 0;
}
my input file is:
我的输入文件是:
p1 0 20.0
p2 2 15.0
p3 6 27.0
p4 4 36.0
and my output is:
我的输出是:
p1p2p3p4 0 20.000000
p2p3p4 2 15.000000
p3p4 6 27.000000
p4 4 36.000000
I don't know why in first line of output along with p1, p2p3p4 is coming and same for 2 and 3 line.
我不知道为什么在输出的第一行和p1,p2p3p4和2和3行相同。
1 个解决方案
#1
3
Remember that strings in C have a special terminator character, so a string of two characters actually needs to be three characters long.
请记住,C中的字符串有一个特殊的终止符,因此两个字符的字符串实际上需要三个字符长。
If you do not have the space for the terminator character, then your fscanf
call will write that special terminator out of bounds of your array, leading to undefined behavior.
如果没有终结符字符的空间,那么你的fscanf调用会将特殊的终结符写入数组的边界之外,从而导致未定义的行为。
The fix is very simple, change the declaration of pno
to this:
修复非常简单,将pno的声明更改为:
char pno[max][3];
You might also want to change that fscanf
call, to make sure that it will not attempt to store more than two (not including the terminator) characters in the array:
您可能还想更改该fscanf调用,以确保它不会尝试在数组中存储两个以上(不包括终止符)字符:
fscanf(fp, "%2s %d %f" ,pno[n],&at[n],&bt[n])
This will help in case the input file is corrupted in some way.
如果输入文件以某种方式损坏,这将有所帮助。
You might also want to change the condition to e.g.
您可能还想将条件更改为例如
while (fscanf(...) != 3)
as that will also detect problems with the input file.
因为这也会检测输入文件的问题。
#1
3
Remember that strings in C have a special terminator character, so a string of two characters actually needs to be three characters long.
请记住,C中的字符串有一个特殊的终止符,因此两个字符的字符串实际上需要三个字符长。
If you do not have the space for the terminator character, then your fscanf
call will write that special terminator out of bounds of your array, leading to undefined behavior.
如果没有终结符字符的空间,那么你的fscanf调用会将特殊的终结符写入数组的边界之外,从而导致未定义的行为。
The fix is very simple, change the declaration of pno
to this:
修复非常简单,将pno的声明更改为:
char pno[max][3];
You might also want to change that fscanf
call, to make sure that it will not attempt to store more than two (not including the terminator) characters in the array:
您可能还想更改该fscanf调用,以确保它不会尝试在数组中存储两个以上(不包括终止符)字符:
fscanf(fp, "%2s %d %f" ,pno[n],&at[n],&bt[n])
This will help in case the input file is corrupted in some way.
如果输入文件以某种方式损坏,这将有所帮助。
You might also want to change the condition to e.g.
您可能还想将条件更改为例如
while (fscanf(...) != 3)
as that will also detect problems with the input file.
因为这也会检测输入文件的问题。