0

I am working on code for one of my classes and I have hit a wall. I need the user to input a number that will be used as the number of times a for loop will be repeated. The first loop where I ask for this number is a while loop. I need to make sure the value entered is a number and not a letter or special character.

I do not know how to make sure that it is not a letter or special character.

The next problem is making sure that the for loop only runs for the specified number of times that is the number provided in the first loop.

This is what I have written so far.

#include <stdio.h>

int main()

{

int num_of_scores, n;
char enter;
float score=-1, total=0, average;

do
{
    printf("\n\nEnter the number of quiz scores between 1 and 13: ");
    scanf ("%d, %c", &num_of_scores, &enter);
}
while(num_of_scores<1 || num_of_scores>13/* && enter == '\n'*/);

printf("\nStill Going!");

for(n=0; n<num_of_scores; n++)
{
    printf("\nEnter score %i: ", n+1);
    scanf ("%f", &score);
    while(score>=0 || score<=100)
    {
        total = total + score;
        score = -1;
        break;
    }
}


average = total / num_of_scores;

printf("\nThe average score is %.0f.\n\n", average);
return 0;

}

So I have edited the code a little bit. There is a part in the first while loop that is in a comment which i removed because it made the program end after that loop. The printf("still going") is just a test to make sure the program gets that far. Any further pointers? I am still not sure how to check make sure a number is not entered. I though adding the && enter == '\n' would do it, but if it hangs the program it is no good. Many of the examples you have suggested are good, but i find them a little confusing. Thanks!

jeaboswell
  • 15
  • 3

3 Answers3

1

Check the return value of scanf. Per the man page:

RETURN VALUE

These functions return the number of input items successfully matched and assigned, which can be fewer than provided for, or even zero in the event of an early matching failure.

The value EOF is returned if the end of input is reached before either the first successful conversion or a matching failure occurs. EOF is also returned if a read error occurs, in which case the error indicator for the stream (see ferror(3)) is set, and errno is set indicate the error.

abligh
  • 24,573
  • 4
  • 47
  • 84
1

I'd check Check if input is integer type in C for the answer to this...

Community
  • 1
  • 1
Kiradien
  • 104
  • 6
0
do{
    char ch = 0;
    num_of_scores = 0;
    printf("\nEnter the number of quiz scores between 1 and 13: ");
    if(scanf("%d%c", &num_of_scores, &ch)!=2 || ch != '\n'){
        int ch;
        while((ch=getchar())!='\n' && ch !=EOF);
    }
} while(num_of_scores<1 || num_of_scores>13);
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70