Home > database >  Scanf() not working correctly in C when inputting value
Scanf() not working correctly in C when inputting value

Time:09-26

I'm trying to work on a program to input a phone number and test if it is the right amount of digits in C, also checking if the first value is not 0 or 1. Scanf is not taking a value when I enter it and I do not understand why. If someone could please point out to me what the issue is it'd be much appreciated. Thanks.

#include <stdio.h>

int main (void){

    int number = 0;
    int loop = 0;

    while(loop == 0){

        printf("Enter a phone number: ");
        scanf(" %d ", &number);
        printf("%d", number);
        
        int firstDigit;
        while(number >= 10){
                firstDigit = number/10;
            }

        if((number/1000000) >= 1 && (number/1000000) < 10){
            if(firstDigit == 1){
                printf("Invalid central office code: 1");
            }
            else if(firstDigit == 0){
                printf("Invalid central office code: 0");
            }
            else{
                int firstThree = (number/10000);
                int lastFour = (number%10000);
                printf("%d - %d", firstThree, lastFour);
            }
            
        }
        
        else if(number == 0){
            printf("Exiting.");
            loop = 1;
        }

        else{
            if((number/1000000)>=10){
             printf("Invalid phone number: too many digits");
            }
            else if((number/1000000)<1){
                printf("Invalid phone number: too few digits");
            }
        }
    
    }
    
    return 0;
}

CodePudding user response:

This:

while(number >= 10) {
    firstDigit = number/10;
}

is an infinite loop, because you are not modifying number.

What you probably want to do is:

while(number >= 10) {
    firstDigit = number/10;
    number /= 10;
}

You should avoid scanf() to read input. Better use fgets(), and then sscanf() for parsing.

char input[1024]; // This should be large enough
if (!fgets(input, sizeof input, stdin)) {
    printf("Input error\n");
    return 1;
}

input[strcsnp(input, "\n")] = '\0'; // Because fgets reads \n so remove it

if (sscanf(input, "%d", &number) != 1) {
    printf("Parsing error\n");
    return 1;
}

// Use number...

Also, scanf() and sscanf() "ignore" the first 0s you type as part of the phone number, so your solution might not be correct. The best way to represent a phone number is either by storing it as a string (as mentioned in a comment), or by defining a phone number structure.

CodePudding user response:

Int size in c is 4 bytes, which can hold values only -2,147,483,648 to 2,147,483,647. It can't store all 10 digit values.

you can use long

long number = 0;
scanf("%ld", &number);
printf("%ld", number);
  •  Tags:  
  • c
  • Related