我正在尝试使用 txt 文件中的结构创建链表。最初,我使用只有一行信息的 txt 文件对其进行测试。这段代码编译正确,但是当我运行它时,它返回“Line...didn't scan properly”。顺便说一句,如果我删除返回这样一个值的 if 语句,我就会完全乱码。我不知道为什么没有正确扫描该行,但我觉得它可能与我尝试扫描为字符串的两个术语中的连字符/加号有关。非常感谢您提供的任何帮助。
这是txt文件:
1 20959U 90103A 14091.58762725 -.00000015 00000-0 00000+0 0 3197
这是 tester.c 文件:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct noradData {
// line one
int lineNum;
char * satNum;
char * intDesig;
float epoch;
float firstTimeDeriv;
char * secondTimeDeriv;
char * drag;
int zero;
int set;
struct noradData * next;
} Data;
Data * first = NULL, * last = NULL;
int main() {
char line[80], secondTimeDeriv[7], drag[7], satNum[6], intDesig[6];
int lineNum, zero, set;
float epoch, firstTimeDeriv;
FILE * fIn;
Data * node;
fIn = fopen("data1.txt", "r");
if (fIn == NULL) {
printf("Cannot open file\n");
return 1;
}
while (fgets(line, sizeof(line), fIn) != NULL) {
// Check line for various problems (too short, too long).
if (line[0] == '\0') {
printf ("Line too short\n");
return 1;
}
if (line[strlen (line)-1] != '\n') {
printf ("Line starting with '%s' is too long\n", line);
return 1;
}
line[strlen (line)-1] = '\0';
// Scan the individual fields.
if (scanf("%d %s %s %f %f %s %s %d %d", &lineNum, satNum, intDesig,
&epoch, &firstTimeDeriv, secondTimeDeriv, drag, &zero, &set)
!= 9) {
printf ("Line '%s' didn't scan properly\n", line);
return 1;
}
node = malloc(sizeof(Data));
if (node == NULL) {
printf ("Ran out of memory\n");
return 1;
}
node->lineNum = lineNum;
node->satNum = strdup(satNum);
node->intDesig = strdup (intDesig);
node->epoch = epoch;
node->firstTimeDeriv = firstTimeDeriv;
node->secondTimeDeriv = strdup(secondTimeDeriv);
node->drag = strdup(drag);
node->zero = zero;
node->set = set;
node->next = NULL;
if (first != NULL) {
last->next = node;
last = node;
}
else {
first = node;
last = node;
}
}
fclose (fIn);
node = first;
while (node != NULL) {
printf("%d %s %s %f %f %s %s %d %d", node->lineNum, node->satNum,
node->intDesig, node->epoch, node->firstTimeDeriv,
node->secondTimeDeriv, node->drag, node->zero, node->set);
node = node->next;
}
return 0;
}
最佳答案
首先将字符数组 satnum 和 intdDesig 的大小更改为 7 即 satnum[7] 和 intDesig[7]。你想在这些中存储 6 个字符,最后一个索引为空值。
if (line[strlen (line)-1] != '\n') {
printf ("Line starting with '%s' is too long\n", line);
return 1;
}
这个 if 语句而不是 line[strlen(line)-1]!='\n' 放这个-
line[strlen(line)-1]=='\n'
语句是这样的
if (line[strlen (line)-1]=='\n') {
printf ("Line starting with '%s' is too long\n", line);
return 1;
}
并删除这一行
line[strlen (line)-1] = '\0';
那么行将不会被返回两次。
关于c - 使用 C 中的结构将文本读入链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31108447/