使用以下代码:
char *name = malloc(sizeof(char) + 256);
printf("What is your name? ");
scanf("%s", name);
printf("Hello %s. Nice to meet you.\n", name);
用户可以输入他们的名字,但是当他们输入带有空格的名字时,如 Lucas Aardvark
, scanf()
在Lucas
之后切断一切.我如何制作 scanf()
允许空格
最佳答案
人们(和尤其是初学者)不应该使用scanf("%s")
或gets()
或任何其他函数没有缓冲区溢出保护,除非您确定输入将始终是特定格式(甚至可能不是)。
请记住,scanf
代表“扫描格式化”,而且除了用户输入的数据之外,less 格式非常宝贵。如果您可以完全控制输入数据格式,但通常不适合用户输入,那么这是理想的选择。
使用 fgets()
(具有 缓冲区溢出保护)将您的输入转换为字符串,并使用 sscanf()
对其求值。由于您只需要用户输入的内容而不进行解析,因此在这种情况下您实际上并不需要 sscanf()
:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Maximum name size + 1. */
#define MAX_NAME_SZ 256
int main(int argC, char *argV[]) {
/* Allocate memory and check if okay. */
char *name = malloc(MAX_NAME_SZ);
if (name == NULL) {
printf("No memory\n");
return 1;
}
/* Ask user for name. */
printf("What is your name? ");
/* Get the name, with size limit. */
fgets(name, MAX_NAME_SZ, 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);
/* Free memory and exit. */
free (name);
return 0;
}
关于c - 如何允许使用 scanf 输入空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1247989/