gpt4 book ai didi

c - 第一次没有读取字符串

转载 作者:太空宇宙 更新时间:2023-11-04 01:08:30 25 4
gpt4 key购买 nike

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef char* string;

int main(void)
{
char *names[6];
int num_entries = 0,i=0,size=0;
string name = (string) malloc(sizeof(char) * 16);

printf("\nHow many names do you want to enter ? \n");
scanf("%d",&num_entries);

for(i=0 ; i < num_entries ; i++)
{
printf("\nEnter a name : ");
gets(name);
size = strlen(name);
names[i] = (string) malloc(sizeof(char)*size + 1);
strcpy(names[i],name);
}

for(i=0 ; i < num_entries ; i++)
puts(names[i]);

}

在这个程序中,字符串不是第一次在循环中读取,但是对于所有后续调用都可以正常工作,程序只需要接受 n 个字符串,存储并显示它们。无论它执行 n-1 次。解决方案?另外,请随时指出指针、分配等使用方式中的任何错误,感谢任何反馈。

最佳答案

在循环之前调用gets来丢弃scanf留下的新行。

或者更好的是,使用标准的解决方法丢弃未读输入:

int c;
while ((c = getchar()) != '\n' && c != EOF);

关于c - 第一次没有读取字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18291918/

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