Reputation: 185
I have a text file containing only letters that looks like so:
AAAA
BBBB
CCCC
I am attempting to go through the file and save all of the characters in a string. Here is my code:
// Set sequence variable to sequence in file
for ( seqlength = 0; (symbol = getc(f)) != EOF;){ //seqlength is an int
//symbol is a char
//f is a file pointer
if ( symbol != '\n'){
sequence[seqlength] = symbol; //sequence is a char[]
seqlength++;
}
}
When I print out printf("sequence: %s length: %d\n", sequence, strlen(sequence));
after this loop completes, I get the AAAABBBBCCCC
string as expected, but with a bunch of garbage characters after the last C and a strlen
of 22 when 12 is expected.
Can anyone provide a simple fix to this to make it work?
Thanks
Edit: I would like to also add that the non alphanumeric character appears to change every time when I run the code and print it to the console. Using the GCC compiler in Code::Blocks.
Upvotes: 0
Views: 185
Reputation: 206577
The garbage you see is the result of failing to terminate the string with the null character.
for ( seqlength = 0; (symbol = getc(f)) != EOF;){ //seqlength is an int
//symbol is a char
//f is a file pointer
if ( symbol != '\n'){
sequence[seqlength] = symbol; //sequence is a char[]
seqlength++;
}
}
// Terminate string with the null character.
sequence[seqlength] = '\0';
Upvotes: 1