Friday, December 18, 2009

C input routine for single character and string

By answering some beginner questions in the programming forum, I am trying to learn some C/C++ again. As a matter of course, I learned something new as always, this is a page I referred to when trying to clear the buffer in stdin.

The first example is for capturing single character and check if it is a number between 1 and 4:

char option;
int number;
do {
puts("Please enter your choice:");
fflush(stdout);
if (fgets(&option, 2, stdin) != NULL) {
if (option != '\n') {
scanf("%*[^\n]"); // get rid of the non-newline characters
scanf("%*c"); // get rid of the newline character
}
}
} while (!(sscanf(&option, "%d", &number) == 1 &&
number >= 1 && number <= 4));


The 2nd example is for capturing a string with trimming, overflow protection and emptyness checking:


char fileStr[20];
char *pointer = fileStr;
bool tooLong = false;

do {
printf("\nPlease input a file name: ");
fflush(stdout);
if (fgets(fileStr, sizeof fileStr, stdin) != NULL) {
tooLong = false;
if (*fileStr != '\n') {
// search for newline character
char *newline = strchr(fileStr, '\n');
if (newline != NULL) {
*newline = '\0'; /* overwrite trailing newline */
pointer = trimwhitespace(pointer); /* trim the line */
} else {
/* clear the stdin since user input too much */
tooLong = true;
scanf("%*[^\n]");
scanf("%*c");
}
}
}
} while (tooLong || *pointer == '\0' || *pointer == '\n');

printf("file name = \"%s\"\n", pointer);


Pay special attention on the variable you are gonna use at last, it is "pointer".

No comments: