Nate Brisson
Nate Brisson

Reputation: 9

scanf Terminating Program

I am trying to write a program in C that converts a base n number to base 10. I have 4 functions not including main: ObtainNumber, GetBase, ConvertNumberToBase10, GetMyExponential. My main function executes the functions in the following order: GetBase, ObtainNumber, GetMyExponential, ConvertNumberToBase10. My program runs both the GetBase function and the ObtainNumber function. However, I use a scanf function in my ObtainNumber function and the program does not continue on to the other functions:

    long int ObtainNumber (long int myNumber)
    {

        scanf("%ld", &myNumber);
        while (myNumber > 999999999)
            {
                printf("Error. Please enter a number with no greater than 9 digits\n");
                scanf("%ld", &myNumber);
            }

        return (myNumber);

}

I was wondering why this is happening and how I could fix it?

Upvotes: 0

Views: 1667

Answers (1)

Keith Thompson
Keith Thompson

Reputation: 263237

The scanf() function returns a result of type int, which is either the number of items successfully scanned, or the value EOF if there was an error. You should always check the result, since scanf() can fail due to circumstances beyond your program's control.

scanf("%ld", ...) will, after skipping leading whitespace (including newlines), read text with the syntax of an optionally signed integer constant. Anything following that is left in the input stream.

Without seeing more of your code and the input you're giving it, it's difficult to tell what the problem is.

Using scanf can be tricky. A better approach is to use fgets() to read an entire line of input, then sscanf() to interpret its contents. By using fgets(), you won't be leaving partial input lines waiting for the next call (unless the line is longer than your input buffer), and if the sscanf() call fails, it doesn't affect the state of the input stream.

Note, use fgets(), not gets(); gets() is inherently unsafe, should never be used, and has been removed from the language standard.

Upvotes: 1

Related Questions