Skip to content

Instantly share code, notes, and snippets.

@alexcu
Last active April 30, 2018 08:05
Show Gist options
  • Save alexcu/328164b582913fdced9fa7809cc2a6a6 to your computer and use it in GitHub Desktop.
Save alexcu/328164b582913fdced9fa7809cc2a6a6 to your computer and use it in GitHub Desktop.
// ============================
// = User Input Function in C =
// ============================
#include <stdio.h>
//
// The my_string type can be used to represent a "string" in C.
// This needs to be a struct so that it can be returned from
// functions.
//
typedef struct my_string
{
char str[256]; // my string contains an array of 255 characters + null
} my_string;
//
// Reads a string of up to 255 characters + 1 for null
//
my_string read_string(const char* prompt)
{
my_string result;
printf("%s", prompt);
scanf(" %255[^\n]", result.str );
return result;
}
//
// Reads a integer from the user.
//
int read_integer(const char* prompt)
{
my_string line;
int num;
char temp; //used to check nothing comes after the int
line = read_string(prompt);
// scan the string, looking for a number ... followed by nothing
while ( sscanf(line.str, " %d %c", &num, &temp) != 1 )
{
// scan found a number followed by something... so its not a whole number
printf("Please enter a whole number.\n");
line = read_string(prompt);
}
return num;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment