Skip to content

Instantly share code, notes, and snippets.

@chrismanderson
Created October 6, 2014 21:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrismanderson/012bfc5cce6123fc2aeb to your computer and use it in GitHub Desktop.
Save chrismanderson/012bfc5cce6123fc2aeb to your computer and use it in GitHub Desktop.
getInt
int GetInt(void)
{
// try to get an int from user
while (true)
{
// get line of text, returning INT_MAX on failure
string line = GetString();
if (line == NULL)
{
return INT_MAX;
}
// return an int if only an int (possibly with
// leading and/or trailing whitespace) was provided
int n; char c;
if (sscanf(line, " %d %c", &n, &c) == 1)
{
free(line);
return n;
}
else
{
free(line);
printf("Retry: ");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment