gpt4 book ai didi

c - 从c程序中读取文件中的行得到错误的输出

转载 作者:太空宇宙 更新时间:2023-11-03 23:40:52 25 4
gpt4 key购买 nike

我需要得到这个输出:

P1  0   3
P2 1 6
P3 4 4
P4 6 2

但是我得到的是:

0   0   0
0 0 0
0 0 0
0 0 0

我是 C 编程的新手。所以,我不知道为什么我得到错误的输出。这就是我所做的。我应该将每一列存储在不同的变量中。因为将它们存储在不同的变量中后,我需要对它们进行数学计算。

#include<stdio.h>
#include<stdlib.h>
#include <string.h>
#include <math.h>
#include <stdint.h>
#include <stdbool.h>

int main (int argc, char *argv[]) {

FILE *fptr;

fptr = fopen(argv[1], "r");

if (fptr != NULL) {
size_t i;
int SIZE = 1000;
int*x[500];
int*y[500];
int*z[500];
int ch=0;
int l;
int n=0;
char line[100];

while ((ch=fgetc (fptr))!= EOF) {
if (ch=='\n')
n++;
}

printf("Number of lines = %d\n", n);

for (l=0; l<n;++l) {
while(fgets(line,sizeof line,fptr)) {
printf("%s",line);
sscanf(line,"%d %d %d",&x[l],&y[l],&z[l]);
}
}

for (i=0; i<l;++i) {
printf("%d %d %d\n",x[i],y[i],z[i]);
}

fclose(fptr);
return 0 ;
}

最佳答案

我至少看到 2 个问题。

  1. fptr 在计算行数时已到达文件末尾。所以 rewind() fptr 在计数行之后,因为它已经到达文件末尾。所以在第一个 while 循环之后添加 rewind(fptr)

  2. 您不需要 x, y, z 作为指针数组,而只是一个数组。所以把它们改成

    int x[500]; 
    int y[500];
    int z[500];

关于c - 从c程序中读取文件中的行得到错误的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46356705/

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