C 通过fgets()接受用户的多行输入
我试图使用C 通过fgets()接受用户的多行输入,c,segmentation-fault,fgets,C,Segmentation Fault,Fgets,我试图使用fgets从用户那里接受多行“地址”,但在我离开while循环时,出现了分段错误(内核转储)。我可以printf循环中的address和part\u\u\u-address变量没有任何问题,而在循环中它按预期工作。一旦从线圈中挣脱,它就会着火 // Define a char array called 'name' accepting up to 25 characters. char name[25]; // Define a char array called 'part_of_a
fgets
从用户那里接受多行“地址”,但在我离开while循环时,出现了分段错误(内核转储)
。我可以printf
循环中的address
和part\u\u\u-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...");
正如Michael Walz在评论中指出的,您使用的是strcat(地址,地址的一部分)代码>即使第一次没有初始化
地址
。因为它是一个自动数组,所以它包含未确定的值,并且您正在调用未定义的行为。很可能,即使是第一个strcat
也会覆盖地址
数组之后的内存
只需使用
字符地址[80]=“初始化数组即可代码>或字符地址[80]={'\0'}
通过重复将文本连接到地址
,很可能会溢出该地址。如果用户从未输入地址,则会出现分段错误。地址
未初始化<代码>字符地址[80]代码>->字符地址[80]=“”代码>.BTW:使用调试器可以很容易地找到此类错误。学习如何使用它,那么你的教授就不会教你任何有用的东西了。