0

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.

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

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

1
  • Post the definition of id. Is it char id[4]? If so ` structures[i].id[4] = '\0'` is bad. Commented Nov 25, 2014 at 0:48

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.