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

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

问题描述

使用以下code:

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

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

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

一个用户可以输入自己的名字,但是当他们进入一个名字像卢卡斯土豚空格scanf()的只是卢卡斯后切断一切。如何让 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)获得()或没有缓冲区溢出保护,除非你肯定知道的输入将永远是一个特定格式的(也许任何其他职能甚至没有的话)。

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函数表示扫描格式,并有precious小的的格式不是用户输入的数据。这是理想的,如果你有输入数据格式的完全控制,但一般不适用于用户输入。

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\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;
}

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

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