我尝试了在该网站上找到的代码( 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);
当我在 main 中运行这段代码时,它运行得很好。输出为:
What is your name? j k rowling
Hello j k rowling. Nice to meet you.
但是当我将此代码放入 while 循环或 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; }
输出为:
What is your name? Hello . Nice to meet you.
因此,它不会等待输入字符串。也许 fgets 不起作用,我不知道。
我怎样才能让这段代码工作?或者从输入中获取所有空格的字符串的任何替代方法。我尝试过这个:
switch (choice) {
case 1:
printf("What is your name? ");
scanf("%[^\n]s", name);
printf("%s\n", name); }
输出为:
What is your name? ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠
这些有什么问题吗?我使用 Visual Studio 。而我总是遇到麻烦。是关于这个的吗?
最佳答案
问题是 stdin
没有正确刷新。
您需要手动刷新它。 (fflush() 函数可用。但是有问题。)
以下是解决您的问题的示例代码。查看working here :
#include <stdio.h>
#define MAX 15
int main(void) {
// your code goes here
char name[MAX];
char c;
int choice=1;
while(choice>0 && choice<3)
{
printf("Enter your choice: ");
scanf("%d", &choice);
switch(choice)
{
case 1:
//Flush stdin
while ((c = getchar()) == '\n');
ungetc(c, stdin);
printf("What is your name? ");
fgets(name, MAX, stdin);
if ((strlen(name) > 0) && (name[strlen(name) - 1] == '\n'))
name[strlen(name) - 1] = '\0';
printf("Hello %s. Nice to meet you.\n", name);
break;
case 2:
printf("Your choice is case 2\n");
break;
}
}
return 0;
}
关于c - 从 switch case 或循环中的输入获取带空格的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50127809/