gpt4 book ai didi

c - scanf 在此 C 程序中无法正常工作

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

我写了一段小代码来获取从华氏度到摄氏度的值。我想一直输入数据,直到我按下“y”以外的任何其他键。但是这个循环不是那样工作的,它会在一次迭代后停止。

#include <stdio.h>

int main()
{
char ch='y';
int far, cen;
do {
printf("again\n");
scanf("%d",&far);
//cen = (5.0/9.0)*(far-32);//integer division will truncate to zero so we can make 5/9 to 5.0 / 9.0
cen = (5*(far-32))/9;//or this way we can use this formula
printf("\n%d\t%d",far, cen);
printf("ch=%c",ch);
scanf("%c",&ch);
}while(ch == 'y');

return 0;
}

这里有什么问题?附言我添加了一行并制作了一个这样的新代码

#include <stdio.h>

int main()
{
char ch='y';
int far, cen;
do {
printf("again\n");
scanf("%d",&far);//here we press carriage return. this value is in stdin
//cen = (5.0/9.0)*(far-32);//integer division will truncate to zero so we can make 5/9 to 5.0 / 9.0
cen = (5*(far-32))/9;//or this way we can use this formula
printf("\n%d\t%d",far, cen);
scanf("%c",&ch);//putting a space before %c makes the newline to be consumed and now it will work well
if((ch == '\r')|| (ch == '\n'))
printf("1\n");
printf("ch=%c",ch);//this takes the carriage return in stdin buffer
}while(ch == 'y');

return 0;
}

我需要知道这里的回车是\r还是\n?

最佳答案

当输入 scanf("%d",&far); 的值并按回车键时,scanf 会将回车符存储在缓冲区中。当它遇到代码 scanf("%c",&ch); 中的第二个 scanf 时,它会将缓冲区中存在的回车符作为“ch”的输入。所以它不会等待用户输入。

请看帖子here

如其中一个回复所述,解决方案是在 scanf 中放置一个空格

scanf(" %c",&ch);

关于c - scanf 在此 C 程序中无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36905720/

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