C语言 fscanf消耗文件中的第一个字母.我怎么修理它?



我正在为读取.csv文件内容的类编写程序。我在for循环中使用while循环将内容扫描到两个单独的数组中,当它打印内容时,一切都是正确的,除了它缺少文件中的第一个字母。除了允许使用的函数外,不允许使用标准库中的任何函数。

问题代码:

void readFile(FILE *fptr, int size)
{
int i, a;
a = size / 2;
printf("number of lines in readFile is %d:n", size);
double y[50];
char x[50];
for (i = 0; i < a; i++)
{
while (fscanf(fptr,"%c,%lf,", &x[i], &y[i]) ==2);
}
printf("%c, %.2lf: ", x[0], y[0]);
//a loop to make sure it scanned properly by displaying array contents
for (i = 0; i < a; i++)
{
printf("%c, %.2lf:n", x[i], y[i]);
}
}

我尝试了! fof (fptr), != EOF,但这些不应该在我正在学习的入门课中使用。我想不出什么办法来修理它。这是上面程序的输出:

number of lines in readFile is 4:
, 20.00: 
, 20.00:
E, 30.00:
number of lines is 4:

有几个问题…

  1. fscanf格式错误。它需要一个前导空格来跳过换行符。
  2. 除非您打算对readFile中读取的数据进行操作(而不是将其传递给调用方),否则当函数返回时,函数作用域为xy数组将超出作用域。
  3. readFile的调用者应该传递最大数组计数,但让函数确定实际条目数。
  4. 每当我看到两个或多个"并行"时;数组[由同一变量索引],我将使用struct。特别是.csv数据。
  5. .csv文件的形式是:a,bnc,dn而不是a,b,nc,d,n,因此fscanf中末尾的,是不正确的。
  6. 使用数据输入的嵌套循环不起作用。
  7. 无需feof。循环直到fscanf返回值为而不是2.

这是更正后的代码。注释:

#include <stdio.h>
#include <stdlib.h>
// data for single .csv line
struct data {
char x;
double y;
};
// readFile -- read in .csv file
// RETURNS: count of records/lines read
size_t
readFile(FILE *fptr, struct data *arr, size_t size)
// fptr -- open file stream
// arr -- pointer to data array
// size -- maximum number of elements in arr
{
int count = 0;
while (1) {
// check for overflow of array
if (count >= size) {
fprintf(stderr,"readFile: too much data for arrayn");
exit(1);
}
// point to current struct/record
struct data *cur = &arr[count];
// read in the .csv line -- stop on error or EOF
if (fscanf(fptr, " %c,%lf", &cur->x, &cur->y) != 2)
break;
// advance the count of the number of valid elements
++count;
}
return count;
}
int
main(int argc,char **argv)
{
struct data arr[50];
// skip over program name
--argc;
++argv;
if (argc != 1) {
printf("wrong number of argumentsn");
exit(1);
}
// open the input file
FILE *fptr = fopen(argv[0],"r");
if (fptr == NULL) {
perror(argv[0]);
exit(1);
}
// read in the data lines
size_t count = readFile(fptr,arr,sizeof(arr) / sizeof(arr[0]));
fclose(fptr);
// print the array
for (size_t idx = 0;  idx < count;  ++idx) {
struct data *cur = &arr[idx];
printf("%c, %.2f:n",cur->x,cur->y);
}
return 0;
}

下面是我用来测试程序的示例输入:

J,23
D,37.62
F,17.83

程序输出:

J, 23.00:
D, 37.62:
F, 17.83:

最新更新