0

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?

3
  • 2
    it's not clear what you want. If the user types 1234abcde5678, do you want to treat it as 12345678, or 1234 followed by 5678? or do you want to treat it as an error?
    – Tom Tanner
    Aug 16, 2012 at 17:04
  • thereis cin.ignore() to ignore some characters but doesnt check if it is numeric or non-numeric Aug 16, 2012 at 17:06
  • 1
    "I have a C program ..." You could start by showing us what you already have.
    – Robᵩ
    Aug 16, 2012 at 17:23

3 Answers 3

4
  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
1

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;
}
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.