gpt4 book ai didi

c - 通过 fgets() 接受用户的多行输入

转载 作者:行者123 更新时间:2023-11-30 20:21:33 25 4
gpt4 key购买 nike

我尝试使用 fgets 接受用户的多行“地址”,但在我离开时遇到段错误(核心转储) while 循环。我可以在循环内 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...");

最佳答案

正如 Michael Walz 在评论中指出的,您使用 strcat(address, part_of_address);即使第一次没有初始化address 。由于它是一个自动数组,因此它包含未确定的值,并且您正在调用未定义的行为。很可能甚至是第一个 strcat覆盖 address 之后的内存数组。

只需使用 char address[80] = ""; 初始化数组即可或char address[80] = {'\0'};

关于c - 通过 fgets() 接受用户的多行输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42526122/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com