Reputation: 175
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
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
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
Reputation: 67743
goto 1
, or whatever makes sense for your appUpvotes: 4