0

This is a very small part of our college groupwork. We’d have to present our code and explain how each part of the code works.

We wanted to ensure that the user enters an integer and prompt the user to reenter if they didn’t enter a valid number.

We managed to come up with a solution, but I can’t figure out why it works.

While attempting to come up with a solution, we figured using

numberchecker==input\[i\]
if(!(numberchecker==input\[i\]))

However, it does the opposite of what we wanted so I removed the ‘!‘ and now it somehow works? Why/how is this happening? Shouldn’t the if statement only trigger if we enter an integer?

#include <stdio.h>
int main()
{
  int i,x,input[128],answer,numberchecker;  
  printf("Input number of numbers: ");
  scanf("%d",&x);   
  for(i=0;i<x;i++)
  {
    printf("Input number %d:",i+1);
    scanf("%d",&input[i]);      
    numberchecker==input[i];
    if(numberchecker==input[i])
    {
      do
      {
        printf("\nInvalid number! Please try to input a valid number\n\nInput number %d:",i+1);
        scanf("%d",&input[i]);
        numberchecker==input[i];
      }
      while(numberchecker==input[i]);
    }
  }
}
Dominique
  • 16,450
  • 15
  • 56
  • 112
  • 2
    Please try to indent your code (consistently), that will make is *much* easier to read and understand. – Some programmer dude Nov 25 '22 at 08:03
  • 1
    As for your problem, I suggest you read *lines* (as text) with e.g. `fgets` and then try to parse the input (with e.g. `strtol` or `sscanf`). And always check what any `scanf` family function [*returns*](https://en.cppreference.com/w/c/io/fscanf#Return_value). – Some programmer dude Nov 25 '22 at 08:04
  • 1
    Oh and `numberchecker==input[i];` isn't assignment. Typo for `==` versus `=`? – Some programmer dude Nov 25 '22 at 08:05
  • This is my first time posting here sorry, indenting means to properly arrange the code right? –  Nov 25 '22 at 08:06
  • @haunt yes. Like in the samples in your learning material – Jabberwocky Nov 25 '22 at 08:07
  • Thanks for the answers, it was the “==“ that was causing my confusion. Now it is much easier to explain. –  Nov 25 '22 at 08:15
  • @haunt: I've done the indenting. Now you can clearly see which lines of code go together, there's a clearer hierarchy in your code. – Dominique Nov 25 '22 at 08:33

1 Answers1

0

However, it does the opposite of what we wanted so I removed the ‘!‘ and now it somehow works?

It does not reliable work, but rather relies on undefined behavior.


Why/how is this happening?

It is undefined behavior.


Shouldn’t the if statement only trigger if we enter an integer?

No. It is undefined behavior.


Use fgets() to read a line of user input and strtol() for a basis on how to parse it.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256