-2
我試圖用fgets
接受來自用戶的「地址」的多條線路,但我有一個Segmentation fault (core dumped)
就像我離開while循環。我可以在沒有任何問題的循環中printf
兩個address
和part_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...");
初始化數組您最有可能通過反覆串聯文本溢出了'address'。 – StoryTeller
如果用戶從不輸入地址,則會發生分段錯誤。 – kneeki
你可以只用'strcpy()'第一個字符串,然後'strcat()'休息。 – RoadRunner