Fred
Fred

Reputation: 240

How to check if the input is negative?

The program receives an account number from the user and it cannot be negative.

Is there any other way to check if it is negative?

#include <stdio.h>
    
int main(int argc, char * argv[])
{
    int account = 0;
        
    printf("Enter your account number:\n");
    scanf("%d", &account);
        
    while(account<0)
    {
        printf("Error: Enter a valid account number.\n");
        scanf("%d", &account);
    }
}

Upvotes: 0

Views: 1188

Answers (3)

DipStax
DipStax

Reputation: 502

You can only read char from user input safely, so you need to read char * then convert them to an other type. For your problem you can do this:

char account_str[MAX_CHAR];
unsigned int account = 0;
bool check = false;

printf("Enter your account number:\n");
do
{
    fgets(account_str, MAX_CHAR, stdin); // read the account number (as string)
    check = isPosNumStr(account_str);
    // isPosNumStr is a personal function that determine if a string have only
    // digit and is positive
    if (!check) {
        printf("Error: Enter a valid account number.\n"); 
    }
} while (!check)
account = atoi(account_str); // convert string to int

Upvotes: 2

Marco Alonso Medeiros
Marco Alonso Medeiros

Reputation: 21

#include <stdio.h>
/* For the account number you should use a "long" instead a "int", 
And this happens because the account number needs a bigger allocation of memory.
I recomend you to look for "int" limits to understand this.*/

long NumbAccount;

void main(){
    printf("Enter your account number:\n");
scanf("%ld", &NumbAccount);

while(NumbAccount<0)
{
    printf("Error: Enter a valid account number.\n");
    scanf("%ld", &NumbAccount);
}
}

Upvotes: 2

Roberto Caboni
Roberto Caboni

Reputation: 7490

Altough the question doesn't provide the example inputs causing the behavior you notice, you are probably experiencing overflow issues.

int type, in most modern machine swhere it is stored using 4 bytes, can represent integers from -2,147,483,648 to 2,147,483,647. If you provide a value greater than the maximum positive number (INT_MAX) the value would require a bigger number of bytes to be stored, so in the one actually stored the information of the most significant bits is lost, and the resulting value might end up in the negative range. The same can happen also for big negative values.

What you can do is using long integers so that 8 bits are used and the range is bigger: from -9223372036854775808 to 9223372036854775807.

long num;
scanf ("%ld", &num);

What I would like to emphatize is that numbers representation in computers will always be limited whatever is the number of bytes you use. If these limits are not ok for your application requirements you will have to change your approach, either

  • using strtol, which warns you with a proper return value if an overflow or underflow occurs
  • acquiring the whole string and parsing it yourself

Upvotes: 3

Related Questions