我正在尝试从文件中读取文本,格式如下:ID、用户名、文本
当我尝试逐字符存储到节点时,字符串为空。查看评论(帮助**(这是我的代码:
while(fgets(contents, 250, fp) != NULL) // take one line of data, and copy it to contents until EOF is reached
{
i = 0;
post = malloc(sizeof(message)); // allocates dynamic memory for the node struct
while(contents[i] != ',') //copies id digits to a string of digits
{
id[i] = contents[i];
++i;
}
id[i] = ' '; // insert null character at end of string
++i;
while(contents[i] != ',') //copies username to node user entry
{
post->user[i] = contents[i];
++i;
}
post->user[i] = ' '; // insert null character at end of string
//HELP** PRINTING POST->USER PRINTS BLANK
++i;
while(contents[i] != 'n') //copies post text to node user entry
{
post->text[i] = contents[i];
++i;
}
post->text[i] = ' '; // insert null character at end of string
//HELP** PRINTING POST->TEXT PRINTS BLANK
if(post->text[strlen(post->text)] == ',') // if there is a comma at the end of the post, remove it
{
post->text[strlen(post->text)] = ' ';
}
post->id = atoi(id); // convert string of ID to an integer and set it to the nodes ID
addNodeToList(headmessage, post); //adds the node created to the linked list
}
}
以下是链接列表中节点的结构:
typedef struct message
{
int id; //unique integer value
char user[50]; // the username
char text[120]; // the text of the message
struct message *next; //dynamic connection to the next tweet
}message;
带文本文件:
37,userf,hello
96,userd,hello
36,userc,hello
37,userb,hello
123,usera,hello
在上面循环后打印链接列表时:
37: <username supposed to be here>:<text supposed to be here>
96: :
36: :
37: :
123: :
看起来ID确实有效,但字符串不起作用。如果我添加一个调试行来打印它存储的每个字符,它似乎得到了正确的字符,但一旦循环完成打印,字符串就会打印空白
@kaylum解决了这个问题,因为我使用[I]作为节点数组的索引。
它是通过创建另一个索引号(j(来解决的,以存储到节点中的正确索引
很高兴您发现了这个问题。
但是,使用strtok
可以简化代码:
// take one line of data, and copy it to contents until EOF is reached
while (fgets(contents, 250, fp) != NULL)
{
// allocates dynamic memory for the node struct
post = malloc(sizeof(message));
char *tok;
// copies id digits to a string of digits
tok = strtok(contents,",");
post->id = atoi(tok);
// copies username to node user entry
tok = strtok(NULL,",");
strcpy(post->user,tok);
// HELP** PRINTING POST->USER PRINTS BLANK
// copies post text to node user entry
tok = strtok(NULL,",n");
strcpy(post->text,tok);
// adds the node created to the linked list
addNodeToList(headmessage, post);
}
此时发布的代码:
post->user[i] = contents[i];
变量i
已经远远超过了user
字段的末尾。
I。E.在进入读取user
信息的循环之前,需要这样的语句:int j = 0;
然后
post->user[j] = contents[i];