无法读取所有字符串

标签 c string scanf fgets

int main()
{
int epilogi,n=1,x,i;
char temp[2];
list=malloc(n*sizeof(struct address));
printf("Lista taxidromikon dieuthinseon\n");
printf("1. Eisagogi stoixeion\n");
printf("2. Diagrafi stoixeion\n");
printf("3. Emfanisi listas\n");
printf("4. Eksodos\n\n");
printf("Epilekste dinontas dinontas ena arithmo apo to 1 eos to 4\n");
while (scanf("%d", &epilogi)!=4)
{
if (epilogi==1)
{
while (strcmp("n",temp))
{
printf("Dose onomateponimo, dieuthinsi, poli, xora kai taxidromiko kodika\n");
fgets(list[n-1].name,80,stdin);
fgets(list[n-1].addr,50,stdin);
fgets(list[n-1].city,50,stdin);
fgets(list[n-1].country,30,stdin);
scanf("%[^\n]%d", &list[n-1].code);
printf("------------------------------------\n");
printf("Thelete na eisagete allo stoixeio?(Pliktrologiste y gia nai n gia oxi)\n");
fgets(temp,2,stdin);
printf("\n");
if (strcmp("n",temp))
{
n=n+1;
list=realloc(list,n*sizeof(struct address));
}
} 

[编辑] 好的,我解决了 90% 的问题。现在程序成功要求我输入全部 6 个字符,但不输入临时字符串。那是因为最后一次 scanf 创建的缓冲区中有一个换行符。如何让 fgets 忽略它?

最佳答案

您是否使用 -Wall 选项进行编译? 线路

scanf("%d", list[n-1].code);

如果list是指向struct地址的指针应该产生警告,因为你应该传递code的地址。尝试一下

scanf("%d", &list[n-1].code);

,它对我有用。按照建议,保留字符串的 fgets

关于无法读取所有字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27886725/

相关文章:

c - scanf() 不读取数字 0 或读取错误

c - 在 C 中输入到多数组

c - 斐波那契递归

android - 使用 TextWatcher 在 EditText 中设置最大字数限制

python - 从 Python 中的 year-mm-dd 行中切出年份

C - sscanf 不忽略空白

c - 没有明确长度的 sizeof 数组

c - 在 Linux 上以相反顺序接收的实时信号

c - C语言中如何通过指针访问矩阵数组的元素?

c++ - 使用迭代器向后迭代