gpt4 book ai didi

c - 将文本文件中的行读入数组

转载 作者:太空宇宙 更新时间:2023-11-04 01:44:39 24 4
gpt4 key购买 nike

我有一个包含以下行的文本文件:

(0,0) -180.000  77.500  -999.000  -999.000  -999.000  2740.831  45.000  -0.001  -0.001  0.000 458.138 45.000  -999.000
(1,0) -179.500 77.500 -999.000 -999.000 -999.000 2740.831 45.000 -0.001 -0.001 0.000 458.138 45.000 -999.000
(2,0) -179.000 77.500 -999.000 -999.000 -999.000 2740.831 45.000 -0.001 -0.001 0.000 458.138 45.000 -999.000
(3,0) -178.500 77.500 -999.000 -999.000 -999.000 2740.831 45.000 -0.001 -0.001 0.000 458.138 45.000 -999.000
...
...
(359,0) -0.500 77.500 -999.000 -999.000 -999.000 2740.831 45.000 -0.001 -0.001 0.000 458.138 45.000 -999.000

我正在尝试使用以下程序将此文本文件 (buf) 的每一行放入数组 (buffarray) 的单个元素中:

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

#define PI 4*atan2(1,1)

int main(int argc, char *argv[]) {
FILE *fp;
char buf[200];
char *token;
char buffarray[223920];
char filename[150];
int i, j, k;

sscanf(argv[1], "%s", filename);

if ((fp = fopen(filename, "rt")) == NULL) {
printf("Failed in fopen: %s\n", filename);
return -1;
}

while (!feof(fp)) {
fgets(buf, 200, fp);
token = buf;
printf("buf is %s\n", buf);
buffarray++ = token;
}
}

为什么每次编译这个程序时我都会收到一条错误消息:

translate_ww3file.c: In function ‘int main(int, char**)’:
translate_ww3file.c:30:12: error: lvalue required as increment operand
buffarray++ = token;
^

如何解决这个问题?理想情况下,我想创建另一个重新排列行的文本文件,以便首先在新文本文件中打印原始文本的第 180 到 359 行,然后在新文本文件中打印第 1 到 179 行。

最佳答案

多个问题:

  • PI 宏未正确括起来。应该是#define PI (4*atan2(1,1))
  • while (!feof(fp)) 总是错误的。请改用 while (fgets(buf, 200, fp))
  • 你不能递增一个数组,你想用 strcat(buffarray, token); 连接数组末尾的字符串,但你必须初始化 buffarray[0] 到循环之前的 '\0'

这是更正后的版本:

#include <errno.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define PI (4*atan2(1,1))

int main(int argc, char *argv[]) {
FILE *fp;
char buf[200];
char *token;
char buffarray[223920];
char filename[150];

if (argc < 2 || sscanf(argv[1], "%149s", filename) != 1) {
printf("missing command line argument\n");
return 1;
}

if ((fp = fopen(filename, "rt")) == NULL) {
printf("Failed in fopen %s: %s\n", filename, strerror(errno));
return 1;
}

*buffarray = '\0';
while (fgets(buf, sizeof buf, fp)) {
token = buf;
printf("buf is %s\n", buf);
strcat(buffarray, token);
}
fclose(fp);

printf("file contents:\n);
fputs(buffarray, stdout);
return 0;
}

关于c - 将文本文件中的行读入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56013596/

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