循环文本文件时不需要的字符

时间:2014-10-02 04:52:24

标签: c file io

我有一个只包含字母的文本文件:

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编译器。

1 个答案:

答案 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';
相关问题