两个相同的循环,但第二个循环无限延续

时间:2015-09-07 21:31:23

标签: c loops

程序的预期输出是在用户输入的句子周围打印指定字符的边框。

//program: border.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>



int main(int argc, char *argv[]) {
    int argu = argc - 1;

    if(argu < 1){
        printf("usage: border arguments are the text to border.\n");
    }

    else{
        printf("Enter the character for the border: ");
        char in = getchar();//get the character input by user
        int size;
        for(int i = 1; i <= argu; i++){// gets the count of the characters in the string
            size += strlen(argv[i]);
            size += 1; //to compensate for spaces
        }

        printf("%d", size);
        printf("\n");
        size += 2;

        for( int a = 0; a <= size ; a++){
            printf("%c", in); // prints the first border line
        }
        printf("\n");

        printf("%c%*c\n", in, size, in);//prints second line of border line.

        printf("%c", in);
        printf(" ");
        for( int i = 1; i <= argu; i++){//prints the sentence that was typed.
            printf("%s " , argv[i]);
        }
        printf("%c", in);
        printf("\n");

        printf("%c%*c\n", in, size, in);// same as the second line.
        printf("%d", size);



        for( int b = 0; b <= size ; b++){    //causing the infinite loop
            printf("%c", in);
        }

        printf("\n");
    }
    return 0;

我的第一个循环工作正常:

    for( int a = 0; a <= size ; a++){
        printf("%c", in); // prints the first border line
    }

但是当我包含第二个相同的内容时,它会导致我的程序无限继续。

    for( int b = 0; b <= size ; b++){
        printf("%c", in);
    }

1 个答案:

答案 0 :(得分:1)

正如评论中提到的,你永远不会初始化size,这意味着它有一些随机值。因此,您最终会打印一些等于该随机值的边框字符加上预期的边框长度。

如果你这样做:

int size = 0;

这将解决问题。样本输入/输出:

[dbush@db-centos tmp]$ ./x1 test text
Enter the character for the border: x
10
xxxxxxxxxxxxx
x           x
x test text x
x           x
12xxxxxxxxxxxxx

所以现在我们看到有一个数字卡在底部边界。那是因为你在底部边框之前打印size,所以你应该在循环之后将printf移动到打印边框。

所以改变这个:

    printf("%c%*c\n", in, size, in);// same as the second line.
    printf("%d", size);

    for( int b = 0; b <= size ; b++){    //causing the infinite loop
        printf("%c", in);
    }

对此:

    printf("%c%*c\n", in, size, in);// same as the second line.

    for( int b = 0; b <= size ; b++){    //causing the infinite loop
        printf("%c", in);
    }
    printf("%d", size);  // this line moved down