我有一个只包含字母的文本文件:
AAAA
BBBB
CCCC
我试图浏览文件并将所有字符保存在字符串中。这是我的代码:
// 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++;
}
}
当我在这个循环完成后打印出printf("sequence: %s length: %d\n", sequence, strlen(sequence));
时,我按预期得到AAAABBBBCCCC
字符串,但是在最后一个C之后有一堆乱码字符,而在{22}时有strlen
预计12。
任何人都可以提供一个简单的解决方案来使它工作吗?
由于
编辑:我还想补充说,每次运行代码并将其打印到控制台时,非字母数字字符似乎都会改变。在Code :: Blocks中使用GCC编译器。
答案 0 :(得分:1)
您看到的垃圾是无法使用空字符终止字符串的结果。
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';