gpt4 book ai didi

c - 为什么我需要按三次 '\n' 才能运行?

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

嗨,有人知道为什么这段代码让我在运行前按 Enter 三次吗?我需要它才能在第一个 '\n' 运行学校作业这是代码:非常感谢!!

int main()
{
char L1=0, L2=0, L3=0 ;
int count_hya=0, countLA=0, countLC=0, countLH=0, countLL=0 ;
printf("give me some letters\n");

while ((L1!='\n')&&(L2!='\n')&&(L3!='\n'))
{
L1=getchar();
if (L1=='A')
countLA++;
if (L1=='C')
countLC++;
if (L1=='L')
countLL++;
if (L1=='H')
countLH++;
if (L1=='H'&&L2=='Y'&&L3=='A')
count_hya++;
}
printf("number of words begning with: A=%d C=%d L=%d H=%d Hydra=%d",
countLA, countLC, countLL, countLH, count_hya);
return 0;
}

编辑将最后几行更改为:

 if (L1=='H')
{
countLH++;
L2=getchar();
L3=getchar();
if (L1=='H'&&L2=='Y'&&L3=='A')
count_hya++;
}

非常感谢您的帮助!

最佳答案

当你使用的时候:

while ((L1!='\n')||(L2!='\n')||(L3!='\n'))

应该是

while ((L1!='\n')&&(L2!='\n')&&(L3!='\n'))

使用下面的代码

#define SCANF_CHK(L) \
scanf("%c", &L); \
if(L=='\n') continue;

int main()
{
char L1=0, L2=0, L3=0 ;
int count_hya=0, countLA=0, countLC=0, countLH=0, countLL=0 ;
printf("give me some letters\n");
while ((L1!='\n')&&(L2!='\n')&&(L3!='\n'))
{
SCANF_CHK(L1);
SCANF_CHK(L2);
SCANF_CHK(L3);
if (L1=='A')
countLA++;
if (L1=='C')
countLC++;
if (L1=='L')
countLL++;
if (L1=='H')
countLH++;
if (L1=='H'&&L2=='Y'&&L3=='A')
count_hya++;
}
printf("number of words begning with: A=%d C=%d L=%d H=%d Hydra=%d\n",
countLA, countLC, countLL, countLH, count_hya);
return 0;
}

关于c - 为什么我需要按三次 '\n' 才能运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20403623/

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