user1601731
user1601731

Reputation: 175

Keeping characters out of integer input in C

I have a C program that prompts for an input of a 13-digit integer (long long). But the user may accidentally input some characters. How can it avoid crashing or looping by ignoring all the characters in the input?

Upvotes: 0

Views: 132

Answers (3)

Ralph Tandetzky
Ralph Tandetzky

Reputation: 23620

In c I would do it this way:

#include <stdio.h>
#include <string.h>
#include <ctype.h>

int main()
{
    char str[1000];
    int i;
    int newLength = 0;
    long long l;

    scanf( "%s", str );

    for ( i = 0; str[i] != '\0'; ++i )
    {
        if ( isdigit( str[i] ) )
            str[newLength++] = str[i];
    }
    str[newLength] = '\0';
    sscanf( str, "%d", &l );

    return 0;
}

Upvotes: 1

perreal
perreal

Reputation: 97958

You can use scanf:

On success, the function returns the number of items successfully read. This count can match the expected number of readings or fewer, even zero, if a matching failure happens.

Upvotes: 0

Useless
Useless

Reputation: 67743

  1. input a string
  2. check all the characters in the string are digits
    • if the input is invalid: complain and exit, or re-prompt and goto 1, or whatever makes sense for your app
  3. convert your (validated) string to an integer value

Upvotes: 4

Related Questions