hi, i have the following problem::
i want to read a string from the stdin. The string may contain white spaces so {i think} the scanf family of functions is out of the question... I think the most appropriate function for this case is fgets {if i am wrong please correct me}. Fgets is that it stops when it reads an enter in the input stream and problem arises when i use a menu prior to reading a string that causes an enter to be left in the stream... Is there anyway to circumvent this problem? The only way i found is if i call fgets 2 times in a row{so that the first will discart the enter , and the second will read the string}
here is a sample code::
#include <stdio.h>
int Menu()
{
int choice = 0; /* menu choice value */
/* with the following loop we force the user to choose
* on of the 3 valid answers: 1, 2, or 3
*/
do {
fprintf(stdout, "Please choose one of the following:\n"
"1. do1 \n"
"2. do2 \n"
"3. do3 \n");
fscanf(stdin, "%d", &choice);
} while ( choice != 1 && choice != 2 && choice != 3);
return choice;
}
int main()
{
int mychoice = Menu();
printf("\n\n\tyour choice was:: %d\n", mychoice);
printf("\nnow lets read a string with fgets\n", mychoice);
char buffer[256];
fgets(buffer, sizeof(buffer), stdin);
fgets(buffer, sizeof(buffer), stdin);
//fscanf(stdin, "%s", buffer); //unfortunatelly it doesn't work because it stops after reading a white space
printf("\nhere is your string ::: %s\n", buffer);
return 0;
}
thanks in advance for your help,
nicolas
PS:: also another weird behaviour is when instead of a number{in the menu response} i type a letter, then i get in an infinite loop.Why is this happening?