gpt4 book ai didi

c - Scanf 被忽略

转载 作者:行者123 更新时间:2023-11-30 19:42:02 25 4
gpt4 key购买 nike

#include <stdio.h>
#define length 20
main()
{
float x;
int y;
float array1[length], array2[length], array3[length];
float ray[length];
int size1 = insert(array1, length);
printf("enter number: ");
scanf("%d", &y);
int size2 = insert(array2, length);
int size3 = insert(array3, length);
}

int insert(float a[], int size)
{
int n = 0;
while(n<size && scanf("%f\n", &a[n]) == 1)
{
printf("you entered: ");
printf("%2.1f\n", a[n]);
n++;
}
return n;
}

当我运行程序时,它执行第一次插入没问题,但下次调用函数时,scanf()似乎完全被忽略了。我尝试将其放在插入完成的位置之后,但这也被忽略了。

最佳答案

在 scanf 中使用 %*c 来消耗 main() 中 scanf 中的换行符以及 %d 周围的空格。我在 MingW 上测试了以下代码,它似乎有效。 scanf 中的 '\n' 正在被消耗,使其 scanf() 返回,而按下 Enter 键时的 '\n' 仍保留在 IO 缓冲区中,以便再次被 scanf() 消耗;因此出现了奇怪的行为。

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

#define length 20

int insert(float *a, int size)
{
int n = 0;
while(n<size && scanf("%f%*c", &a[n]))
{
printf("you entered: ");
printf("%2.1f\n", a[n]);
n++;
}
return n;
}

int main(int argc, char* argv[])
{
float x;
int y;
float array1[length], array2[length], array3[length];
float ray[length];
int size1 = insert(array1, length);
printf("enter number: ");
scanf("%d", &y);
int size2 = insert(array2, length);
int size3 = insert(array3, length);
return 0;
}

关于c - Scanf 被忽略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32938679/

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