1

I wrote the code to calculate the sum up to a certain number n, if it is not a natural number to write that it is not, or if a number is not entered to say that it was not entered and the program stops working, all that is done, but it simply does not load this part below the if loop, how do I fix that and put returns or some other option?


int main() {
  int i, n, s = 0;
  printf("input n: ");
  scanf("%d", &n);
 if (n<0) {
    printf(" Not natural number");return 0;}
 if (n != scanf("%d", &n)) {
    printf("No number!");return 0;}
  for (i = 1; i <= n; i++)
    s = s + i * i;
  printf("s is: %d", s);
  return 0;
}
erorr98
  • 25
  • 5
  • You can read this: You can try this: https://stackoverflow.com/questions/54073157/input-validation-for-integers-in-c, but the subject is vast. – Jabberwocky Dec 10 '21 at 10:04
  • `n != scanf("%d", &n)` is a bug since it doesn't have well-defined behavior. It is unspecified if the left operand of `!=` is evaluated before or after the right one. – Lundin Dec 10 '21 at 11:02
  • Please don't deface your question as it invalidates the existing answers. – dbush Dec 10 '21 at 18:46

2 Answers2

2

You need to check the return value from scanf to see if the scan was successful. It returns the number of scanned values. Also, error messages should be printed to the standard error stream. Try this:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int c, i, n, s;

    printf("input n: ");    
    c = scanf("%d", &n);
    if (c != 1) {
        fprintf(stderr, "No number!\n");
        exit(EXIT_FAILURE);
    } else if (n < 0) {
        fprintf(stderr, "Not natural number\n");
        exit(EXIT_FAILURE);
    }
    s = 0;
    for (i = 1; i <= n; i++) {
        s = s + i * i;
    }
    printf("s is: %d\n", s);
    return 0;
}
August Karlstrom
  • 10,773
  • 7
  • 38
  • 60
  • This approach works because we quit the program if the input is not valid. If we want to ask for a new input in case of invalid input, it's getting more complicated. – Jabberwocky Dec 10 '21 at 09:59
  • stderr may be used for error messages. There is no requirement. – stark Dec 10 '21 at 12:52
1

Your program logic is wrong:

 if (n<0) {
    printf(" Not natural number");return 0;}
 // here you call scanf  again without any reason
 // just remove the two lines below
 if (n != scanf("%d", &n)) {
    printf("No number!");return 0;}

You want this:

#include <stdlib.h>
#include <stdio.h>

int main() {
  int i, n, s = 0;
  printf("input n: ");
  scanf("%d", &n);
  if (n < 0) {
    printf(" Not natural number"); return 0;
  }

  for (i = 1; i <= n; i++)
    s = s + i * i;
  printf("s is: %d", s);
  return 0;
}

Don't try to validate input with scanf. It can't be done. Don't care about input validation until you are more proficient in C.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115