在C中读取从文件到结构数组的字符串

时间:2022-03-08 11:11:54

I am trying to read strings from file and add them to my array of structs but when i do i get some random characters at the end of one or two strings.Here is my code for reading strings line by line:

我试图从文件中读取字符串并将它们添加到我的结构数组中,但是当我在一个或两个字符串的末尾得到一些随机字符时。这是我逐行读取字符串的代码:

while ((read = getline(&line, &len, fp)) != -1) {
strncpy(&structures[i].id,line,4);   //copies the first four characters to my array of structures
...
}

When i print out the structures[0].id it prints "WW23�" when it should be just "WW23".It does that with couple of strings, although not with all of them. My struct looks like this.

当我打印出结构[0]。它打印“WW23 ”时它应该只是“WW23”。它用几个字符串来做,但不是全部。我的结构看起来像这样。

struct observers
{
 char id[13];
 ...
};

It reads from file properly at least it gets the integer values right.

它正确地从文件读取至少它获得正确的整数值。

2 个解决方案

#1


4  

You are not terminating the string. Add '\0' at the end structures[i].id[4] = '\0'. It should work fine.

你没有终止字符串。在结构[i] .id [4] ='\ 0'处添加'\ 0'。它应该工作正常。

#2


1  

You probably need to add '\0' as the 5'th character to terminate the string.

您可能需要添加'\ 0'作为终止字符串的第5个字符。

#1


4  

You are not terminating the string. Add '\0' at the end structures[i].id[4] = '\0'. It should work fine.

你没有终止字符串。在结构[i] .id [4] ='\ 0'处添加'\ 0'。它应该工作正常。

#2


1  

You probably need to add '\0' as the 5'th character to terminate the string.

您可能需要添加'\ 0'作为终止字符串的第5个字符。