当我在缓冲区中打印内容时,我的代码会打印垃圾值

时间:2013-07-15 17:19:55

标签: c

这是一个程序,用于获取标准输入并显示以换行符结尾的72个字符 如果输入的数量小于72,则必须附加终止空字符,如果我打印缓冲区,我会得到垃圾值。这里有什么问题

int main()  {
int buffer[ MAX_CHAR ];
int count = 0, ch = 0, i = 0;

while( (ch = getchar() != '@') ) {
    // Buffer used to collect the i/p characters from the std i/p
    buffer[count++] = ch;
    if( MAX_CHAR - 1 == count ) {

        buffer[ MAX_CHAR + 1 ] = '\n';
        for(i = 0; i < MAX_CHAR; i++)
            printf("%c", buffer[i]);
        count  = 0;
        buffer[ MAX_CHAR ] = 0;
        }
    }
    //If the input character is less than 72, then append the rest with spaces
    if( count != MAX_CHAR - 1)  {

        for(i = count; i < MAX_CHAR - 1; i++)
            buffer[ count ] = ' ';
        buffer[ MAX_CHAR ] = '\n';
        for(i = 0; i < MAX_CHAR; i++)
            printf("%c", buffer[i]);
        }
   }

1 个答案:

答案 0 :(得分:3)

你有:

while( (ch = getchar() != '@') ) {

这将被解析为:

while( (ch = (getchar() != '@')) ) {

所以ch的值为0或1.你想要的是:

while( ((ch = getchar()) != '@') ) {

此外,通过写入缓冲区的末尾,您在某些地方有未定义的行为:

int buffer[ MAX_CHAR ];
...
buffer[ MAX_CHAR + 1 ] = '\n';
...
buffer[ MAX_CHAR ] = 0;