scanf 接收 空格 输入_你如何允许输入空格使用scanf函数?

本文讨论了在C语言编程中,如何使用scanf函数读取包含空格的用户输入时遇到的问题。当用户输入名字如'Lucas Aardvark'时,scanf会截断在空格后的部分。为了解决这个问题,建议使用fgets函数代替scanf,因为fgets具有缓冲区溢出保护。通过fgets获取用户输入,然后使用sscanf进行评估。示例代码展示了如何使用fgets读取用户输入并移除末尾的换行符,以及如何友好地打招呼。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Using the following code:

char *name = malloc(sizeof(char) + 256);

printf("What is your name? ");

scanf("%s", name);

printf("Hello %s. Nice to meet you.\n", name);

A user can enter their name but when they enter a name with a space like Lucas Aardvark, scanf() just cuts off everything after Lucas. How do I make scanf() allow spaces

解决方案

People (and especially beginners) should never use scanf("%s") or gets() or any other functions that do not have buffer overflow protection, unless you know for certain that the input will always be of a specific format (and perhaps not even then).

Remember than scanf stands for "scan formatted" and there's precious little less formatted than user-entered data. It's ideal if you have total control of the input data format but generally unsuitable for user input.

Use fgets() (which has buffer overflow protection) to get your input into a string and sscanf() to evaluate it. Since you just want what the user entered without parsing, you don't really need sscanf() in this case anyway:

#include

#include

#include

/* 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;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值