通过fgets()接受来自用户的多行输入

时间:2017-03-01 07:56:19

标签: c segmentation-fault fgets

我正在尝试使用fgets接受来自用户的多行'地址',但我离开while循环时我有一个Segmentation fault (core dumped)。我可以printf addresspart_of_address变量在循环内没有任何问题,而在循环中它按预期工作。一旦摆脱了循环,就会着火。

// Define a char array called 'name' accepting up to 25 characters.
char name[25];
// Define a char array called 'part_of_address' accepting up to 80 characters.
char part_of_address[80];
// Define a char array called 'address' accepting up to 80 characters.
char address[80];

// Clean the buffer, just to be safe...
int c;
while ((c = getchar()) != '\n' && c != EOF) {};

// Ask for the user to enter a name for the record using fgets and stdin, store
// the result on the 'name' char array.
printf("\nEnter the name of the user (RETURN when done):");
fgets(name, 25, stdin);

// Ask for the user to enter multiple lines for the address of the record, capture
// each line using fgets to 'part_of_address'
printf("\nEnter the address of the user (DOUBLE-RETURN when done):");
while (1)
{
    fgets(part_of_address, 80, stdin);
    // If the user hit RETURN on a new line, stop capturing.
    if (strlen(part_of_address) == 1)
    {
        // User hit RETURN
        break;
    }
    // Concatinate the line 'part_of_address' to the multi line 'address'
    strcat(address, part_of_address);
}

printf("This doesn't print...");

1 个答案:

答案 0 :(得分:1)

正如Michael Walz在评论中所指出的那样,即使您第一次使用strcat(address, part_of_address);而未初始化address也是如此。因为它是一个自动数组,它包含未终止的值,并且您正在调用未定义的行为。即使在strcat数组之后,第一个address也可能会覆盖内存。

只需使用char address[80] = "";char address[80] = {'\0'};

初始化数组