I think one of the reasons authors of books about programming in C make heavily use
of the function scanf() is that is readily available and easy to use for the new learner.
That's all good and dandy, however when writers of this books get to the more advanced
topics, they fail to remember to go back and say: "by the way, forget about using scanf().
It's a function with a lot of overhead, and full of "gotchas".
I have been looking to make a function of my own that I can use instead of the scanf(), and include in a header of file.
I think, that thanks to you guys, I have a good try here. I intend to create another for reading ints, and reading floats.
What do you think?. Do you see a better way, perhaps?.
I don't like the way I have to pass as a parameter the size of the char array, but I don't
know any other way, besides entering the number amount of elements directly. And that makes it less maintainable.
/*
* read_string.c
* test a function that reads string input and if needed clears the stdin buffer
*/
#include <stdio.h>
int read_string(char *string, int max); /* prototype */
int main(void)
{
char answer[30]; /* a array to store the string up to 29 characters + '\0' */
printf("Enter some text: ");
read_string(answer, sizeof(answer)/sizeof(char)); /* call to read a string input */
puts(answer); /* display the answer for test purpose */
getchar(); /* pause the program until a character is entered */
return(0);
}
/* read_string
parameters:
char *string -> pointer to a string
int max -> maximum number characters to be read */
int read_string(char *string, int max)
{
if(fgets(string, max, stdin) != NULL) /* if input has been entered execute next block */
{
char *newline = strchr(string, '\n'); /* look for the "newline" character and set the pointer to it */
if(newline != NULL) /* Does the pointer points to a character that is not the NULL? */
{
*newline = '\0'; /* the value that newline points to is replaced with a string terminator */
}
else /* if above is not true there's extra characters in the stdin buffer, watch out! */
{
/* get rid off as many characters as there are in the stdin file waiting to screw-up your code */
char ch;
do
{
ch = getchar();
}
while(ch != '\n' && ch != EOF); /* finish when is not longer true */
} /* for the else */
} /* for the first if */
} /* to close the function */