你如何允许使用 scanf 输入空格? [英] How do you allow spaces to be entered using scanf?

查看:28
本文介绍了你如何允许使用 scanf 输入空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用以下代码:

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

printf("What is your name? ");
scanf("%s", name);

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

用户可以输入他们的名字,但是当他们输入一个像Lucas Aardvark这样带有空格的名字时,scanf()只会切断Lucas之后的所有内容代码>.如何让 scanf() 允许空格

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

推荐答案

人们(和尤其是初学者)不应该使用 scanf("%s")>gets() 或任何其他没有缓冲区溢出保护的函数,除非您确定输入将始终具有特定格式(甚至可能不是).

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).

请记住,scanf 代表扫描格式化",并且与用户输入的数据相比,格式化的数据很少更少.如果您可以完全控制输入数据格式,但通常不适合用户输入,则这是理想的选择.

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.

使用 fgets()(具有 缓冲区溢出保护)将您的输入输入到一个字符串中,然后使用 sscanf() 对其进行评估.由于您只想要用户输入的内容而无需解析,因此在这种情况下您实际上并不需要 sscanf() :

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 <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
");
        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] == '
'))
        name[strlen (name) - 1] = '';

    /* Say hello. */

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

    /* Free memory and exit. */

    free (name);
    return 0;
}

这篇关于你如何允许使用 scanf 输入空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆