【发布时间】:2018-05-02 05:42:10
【问题描述】:
我试试这个我在这个网站上找到的代码 (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? ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠
这些有什么问题?我使用视觉工作室。我总是遇到麻烦。这是关于它的吗?
【问题讨论】:
-
你是什么意思“从输入中获取所有空格的字符串”?能举个例子吗?
-
我认为您需要显示Minimal, Complete, and Verifiable example。通常,出现这种问题是因为某些其他输入函数在输入中留下了换行符。
-
你认为 `MAX' 的价值是多少?
-
@J...S MAX 是 15。如果我使用 scanf,我只会从“abc def”中得到“abc”。所以我用 fgets 让所有字符都带有空格。但它只在 main 中有效。
标签: c string input scanf fgets