Skip to content

Instantly share code, notes, and snippets.

@kahless62003
Created April 25, 2016 20:21
Show Gist options
  • Save kahless62003/a9d23512debf9efb3bdd284da6f49a2a to your computer and use it in GitHub Desktop.
Save kahless62003/a9d23512debf9efb3bdd284da6f49a2a to your computer and use it in GitHub Desktop.
Basic user input loop for numbers in range, modified to work with non numeric input and clear rubbish from stdin one of two ways.
#include <stdio.h>
int clean_stdin()
{
while (getchar()!='\n');
return 1;
}
int main(void)
{
int lc1,lc2;/*loop count integers.*/
int input=0;/*variable to hold the maximum count of rows/columns*/
char temp[96];
do
{
printf("Enter size of square [range 1:7]: ");
if(scanf(" %i",&input)==1)
{
if ((input<1) || (input>7))
printf("The input must be in the range [1:7].\n");
}
else
{
printf("The input must be a whole number in the range [1:7].\n");
scanf("%s", temp); /*either clear stdin with another scanf (not recommended)*/
//clean_stdin(); /*or run special function to do it more reliably*/
}
} while ( (input<1) || (input>7) );
printf("Input= %i\n", input);
for (lc1=0;lc1<input;lc1++)
{
for (lc2=0;lc2<input;lc2++)
{
printf("#");
if (lc2 < input-1)
printf("O");
}
if (lc1 < input-1)
printf("\n");
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment