3

I'm trying to create an array that allows me to enter the characters depending on the number that the user has previously entered, if I enter 10 I only want the user to enter 10 characters, A or F. The problem is that it does not work as expected, when entering the number it sends me to the while loop and does not let me exit.

#include <stdio.h>

int main() {
    int i, students;
    char grade[100];

    printf("Welcome, enter the number of students to assign school grade: \n");
    scanf("%d", &students);

    printf("Enter A (Approved) or F (Failure)\n");
    for (i = 0; i < students; i++) {
        printf("School grade for student %d: \n", i + 1);
        scanf("%c", &grade[i]);
        while (grade[i] != 'A' || grade[i] != 'F') {
            printf("Please enter a valid school grade: ");
            scanf("%c", &grade[i]);
        }
    }
    return 0;
}

After I enter the number 10, the program skips the second scanf and sends me into the while loop.

Console error

By changing scanf("%c", &grade[i]) into scanf (" %c", &grade[i]), the problem is that now the while loop is held even when I enter A or F.

Console after put space in scanf

  • 1
    Can you please show the exact input and output you are getting? Likely dup of: [scanf() leaves the new line char in the buffer](https://stackoverflow.com/questions/5240789/scanf-leaves-the-new-line-char-in-the-buffer) – kaylum Aug 31 '20 at 00:13
  • 1
    You enter the number and press enter. scanf takes all the numeric characters and puts them into students. The "enter" key is still in the input and hasn't been removed. So then you read a character and you get the "enter" key which isn't A through F. You need `scanf(" %c", &grade[i]);` (the space in the scanf format string will make it read all the whitespace and then one character) – Jerry Jeremiah Aug 31 '20 at 00:16
  • Does this answer your question? [scanf() leaves the new line char in the buffer](https://stackoverflow.com/questions/5240789/scanf-leaves-the-new-line-char-in-the-buffer) – kaylum Aug 31 '20 at 00:25
  • 2
    `grade[i] != 'A' || grade[i] != 'F'` This will always be true since no grade can be equal to both `A` and `F` at the same time. – dxiv Aug 31 '20 at 00:30

1 Answers1

3

Logic error. Your loop condition is always true.

while (grade[i] != 'A' || grade[i] != 'F')

If the value is A then it is not F. And vice versa.

It looks like you want:

while (grade[i] != 'A' && grade[i] != 'F')

This would loop while any value that is not A or F is entered. It's logically equivalent to:

while (!(grade[i] == 'A' || grade[i] == 'F'))

Please read De Morgan's laws for more information.

paddy
  • 60,864
  • 6
  • 61
  • 103