我正在尝试使用txt文件中的结构创建链接列表。最初,我正在使用仅包含一行信息的txt文件对其进行测试。这段代码编译正确,但是当我运行它时,它返回“Line ...没有正确扫描”。顺便说一句,如果我删除返回这样一个值的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;
}
答案 0 :(得分: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语句代替行[strlen(line)-1]!=&#39; \ n&#39;把这个 -
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';
然后行不会被返回两次。