c - 程序不读取循环中的最后一个字符

标签 c while-loop char scanf

所以我有一个程序,您输入数字“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); 

 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' 

some useful info here

关于c - 程序不读取循环中的最后一个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58945493/

相关文章:

c - 将 1D 二进制数组分解为多个较小的 MPI 数组,没有填充适当的数据,缺少什么?

c - 地址的值(value)。给出异常(exception)

c - 过程识别

c - 为什么我不退出这个 while 循环?

c++ - sscanf 错误 : cannot convert 'String' to 'const char*'

C# 替换字符串中的特殊字符

使用 PAPI_read_counters 计算 L1 缓存未命中会产生意外结果

在 while 循环内记录更改的 Pythonic 方式

C# 减脂计算器

将文字或变量分配给 Char 时的 Scala 行为