0

So I have a program where you input number 'n', and then you input n number of characters. The program tests if you can form a word 'Nice' with those characters. The problem was that whenever I type a character and press enter, the program reads that enter as a character too, so I guess i kinda solved it (?) like this:

    scanf("%c\n")

First of all this seems like a not so good solution even to me (I am pretty much new in this). Another thing is, when i input a number 4, and input letters 'N' 'i' 'c' and 'e', it won't read that last letter 'e' so the program basically doesn't work so well. I hope someone has an explanation for this, and I hope someone could help me. I am sorry if this is a stupid question.

Here is the whole code:

#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.");

}
zoblek
  • 3
  • 1

1 Answers1

0

As mentioned by chux, replace your

scanf("%c\n",&q); 

to

 scanf(" %c",&q);

Why?

When user gives the number of letters is something like "4\n" , this '\n' is taken as your first letter by your second Scanf scanf("%c\n",&q);

printf("Enter the number of letters: ");
scanf("%d",&n); //user input is e.g "4\n"

Second scanf

 printf("Type letter no %d: ",i);
    scanf("%c\n",&q); //Here q takes the value q = '\n' 

some useful info here

owl
  • 56
  • 4