0
int32_t number;
uint32_t x = 1;

puts("What number do you want to count: ?");
{
    scanf("%i", &number);
    printf("You typed%i.\n", number);
    while(x < number) {
        printf("%i and then \n", x);
        x++;
    }
    if (x > 100 || x < 1)
        printf("error");
}

I want to print all the numbers till the user inputs numbers. But if the inputted number is less than 1 or greater than 100 then it should say error and ask the user to input the number again but it does not do that. for instance if the number is 455 it should say error and prompt the user to input the number again.The program above only prints error after printing all the numbers even number grater or less than 100 and 1 respectively.

Swordfish
  • 12,971
  • 3
  • 21
  • 43
Chaite
  • 23
  • 7
  • Why are you comparing uint32_t with int32_t? – user0x0 Sep 26 '18 at 09:56
  • Please [edit] your question and show an example of input and exepected output. – Jabberwocky Sep 26 '18 at 10:00
  • I'd start by quelling your assumption that [`scanf`](https://en.cppreference.com/w/c/io/fscanf) always works.It has a return result for a reason; use it. Don't ignore it. – WhozCraig Sep 26 '18 at 10:03
  • Also, not that when you use %i in scanf, it could read octal and hexadecimal numbers if entered (010 -> 8 in decimal) – user0x0 Sep 26 '18 at 10:08

1 Answers1

2
#include <stdint.h>
#include <stdio.h>

int main(void)
{
    int32_t number;

    while (puts("What number do you want to count? "),  // prompt the user
           scanf("%i", &number) != 1                    // reading an int failed
           || number < 1 || 100 < number)               // number not in range
    {
        fputs("Error!\n\n", stderr);       // print an error message
        int ch;
        while ((ch = getchar()) != EOF && ch != '\n');  // remove garbage left in stdin
    }

    printf("You typed %d.\n", number);

    for(int32_t i = 0; i < number; ++i)
        printf("%i and then\n", i);
}
Swordfish
  • 12,971
  • 3
  • 21
  • 43