I try this code which I found on this website (how-do-you-allow-spaces-to-be-entered-using-scanf)
char name[15]; //or char*name=malloc(15);
/* Ask user for name. */
printf("What is your name? ");
/* Get the name, with size limit. */
fgets(name, MAX, stdin);
/* Remove trailing newline, if there. */
if ((strlen(name) > 0) && (name[strlen(name) - 1] == '\n'))
name[strlen(name) - 1] = '\0';
/* Say hello. */
printf("Hello %s. Nice to meet you.\n", name);
When I run this code in main it works pretty well. Output is:
What is your name? j k rowling
Hello j k rowling. Nice to meet you.
But when I put this code in a while loop or in a switch case:
char name[15];
switch (choice) {
case 1:
printf("What is your name? ");
/* Get the name, with size limit. */
fgets(name, MAX, stdin);
/* Remove trailing newline, if there. */
if ((strlen(name) > 0) && (name[strlen(name) - 1] == '\n'))
name[strlen(name) - 1] = '\0';
/* Say hello. */
printf("Hello %s. Nice to meet you.\n", name);
break; }
The output is:
What is your name? Hello . Nice to meet you.
So, it doesn't wait to entering a string. maybe fgets doesn't work I don't know.
How can I make this code work? Or any alternative to get string from input with all spaces. I tried this either:
switch (choice) {
case 1:
printf("What is your name? ");
scanf("%[^\n]s", name);
printf("%s\n", name); }
output is:
What is your name? ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠
What is wrong with these? I use visiual studio. And I always get a trouble. Is this about it?