所以我有一个程序,您输入数字'n',然后输入n个字符。该程序测试您是否可以使用这些字符组成单词“ Nice”。问题是,每当我键入一个字符并按Enter时,程序也会将该输入读取为字符,因此我想我有点解决了这个问题(?):
scanf("%c\n")
首先,即使对于我来说,这似乎也不是一个很好的解决方案(我对此非常陌生)。另一件事是,当我输入数字4并输入字母“ N”,“ i”,“ c”和“ e”时,它不会读取最后一个字母“ e”,因此该程序基本上无法正常工作。我希望有人对此有解释,也希望有人可以帮助我。如果这是一个愚蠢的问题,我很抱歉。
这是完整的代码:
#include <stdio.h>
#include<stdlib.h>
int main(){
int n,i,a,b,c,d;
char q;
printf("Enter the number of letters: ");
scanf("%d",&n);
i=1;
a=0;
b=0;
c=0;
d=0;
while(i<=n){
printf("Type letter no %d: ",i);
scanf("%c\n",&q);
if(q=='N')
a++;
if(q=='i')
b++;
if(q=='c')
c++;
if(q=='e')
d++;
i++;
}
if(a>0 && b>0 && c>0 && d>0)
printf("Nice.");
else
printf("Not nice.");
}
如chux所述,替换您的
scanf("%c\n",&q);
to
scanf(" %c",&q);
为什么?
[当用户提供字母数时类似“ 4 \ n”,此'\ n'被第二个Scanf当作您的第一个字母scanf(“%c \ n “,&q);
printf("Enter the number of letters: ");
scanf("%d",&n); //user input is e.g "4\n"
第二扫描
printf("Type letter no %d: ",i);
scanf("%c\n",&q); //Here q takes the value q = '\n'