如何使用scanf输入空格?

时间:2009-08-08 04:37:24

标签: c string printf scanf whitespace

使用以下代码:

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()允许空格

12 个答案:

答案 0 :(得分:167)

人们(以及尤其是初学者)绝不应该使用scanf("%s")gets()或任何其他没有缓冲区溢出保护的函数,除非您确定输入将永远是一种特定的格式(也许甚至不是那样)。

请记住,scanf代表“扫描格式化”并且格式比用户输入的数据少 。如果您完全控制输入数据格式但通常不适合用户输入,这是理想的选择。

使用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;
}

答案 1 :(得分:114)

尝试

char str[11];
scanf("%10[0-9a-zA-Z ]", str);

希望有所帮助。

答案 2 :(得分:45)

此示例使用反转扫描集,因此scanf会一直接收值,直到遇到'\ n' - 换行符,因此空格也会被保存

#include <stdio.h>

int main (int argc, char const *argv[])
{
    char name[20];
    scanf("%[^\n]s",name);
    printf("%s\n", name);
    return 0;
}

答案 3 :(得分:21)

您可以使用此

char name[20];
scanf("%20[^\n]", name);

或者这个

void getText(char *message, char *variable, int size){
    printf("\n %s: ", message);
    fgets(variable, sizeof(char) * size, stdin);
    sscanf(variable, "%[^\n]", variable);
}

char name[20];
getText("Your name", name, 20);

DEMO

答案 4 :(得分:7)

在未指定字段宽度的情况下,请勿使用scanf()读取字符串。您还应该检查错误的返回值:

#include <stdio.h>

#define NAME_MAX    80
#define NAME_MAX_S "80"

int main(void)
{
    static char name[NAME_MAX + 1]; // + 1 because of null
    if(scanf("%" NAME_MAX_S "[^\n]", name) != 1)
    {
        fputs("io error or premature end of line\n", stderr);
        return 1;
    }

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

或者,使用fgets()

#include <stdio.h>

#define NAME_MAX 80

int main(void)
{
    static char name[NAME_MAX + 2]; // + 2 because of newline and null
    if(!fgets(name, sizeof(name), stdin))
    {
        fputs("io error\n", stderr);
        return 1;
    }

    // don't print newline
    printf("Hello %.*s. Nice to meet you.\n", strlen(name) - 1, name);
}

答案 5 :(得分:6)

您可以使用fgets()函数读取字符串或使用scanf("%[^\n]s",name);,这样字符串读取将在遇到换行符时终止。

答案 6 :(得分:4)

getline()

现在是POSIX的一部分,毫不逊色。

它还会处理您之前询问的缓冲区分配问题,但您必须处理free内存。

答案 7 :(得分:4)

如果有人还在寻找,那么这对我有用 - 读取包含空格的任意长度的字符串。

感谢网上的许多海报分享这个简单的&amp;优雅的解决方 如果它起作用,信用证归于他们,但任何错误都是我的。

char *name;
scanf ("%m[^\n]s",&name);
printf ("%s\n",name);

答案 8 :(得分:1)

您可以通过一个小技巧将scanf用于此目的。实际上,您应该允许用户输入,直到用户点击Enter(\n)。这将考虑每个角色,包括空间。这是一个例子:

int main()
{
  char string[100], c;
  int i;
  printf("Enter the string: ");
  scanf("%s", string);
  i = strlen(string);      // length of user input till first space
  do
  {
    scanf("%c", &c);
    string[i++] = c;       // reading characters after first space (including it)
  } while (c != '\n');     // until user hits Enter
  string[i - 1] = 0;       // string terminating
return 0;
}

这是如何运作的?当用户从标准输入中输入字符时,它们将存储在 string 变量中,直到第一个空格为止。之后,其余的条目将保留在输入流中,并等待下一个scanf。接下来,我们有一个for循环,它从输入流中获取char(直到\n)并将它们转换为 string 变量的结尾,从而形成一个完整的字符串,如同用户从键盘输入。

希望这会对某人有所帮助!

答案 9 :(得分:0)

虽然你真的不应该使用scanf()来做这类事情,因为有更好的电话,例如gets()getline(),可以这样做:

#include <stdio.h>

char* scan_line(char* buffer, int buffer_size);

char* scan_line(char* buffer, int buffer_size) {
   char* p = buffer;
   int count = 0;
   do {
       char c;
       scanf("%c", &c); // scan a single character
       // break on end of line, string terminating NUL, or end of file
       if (c == '\r' || c == '\n' || c == 0 || c == EOF) {
           *p = 0;
           break;
       }
       *p++ = c; // add the valid character into the buffer
   } while (count < buffer_size - 1);  // don't overrun the buffer
   // ensure the string is null terminated
   buffer[buffer_size - 1] = 0;
   return buffer;
}

#define MAX_SCAN_LENGTH 1024

int main()
{
   char s[MAX_SCAN_LENGTH];
   printf("Enter a string: ");
   scan_line(s, MAX_SCAN_LENGTH);
   printf("got: \"%s\"\n\n", s);
   return 0;
}

答案 10 :(得分:-1)

/*reading string which contains spaces*/
#include<stdio.h>
int main()
{
   char *c,*p;
   scanf("%[^\n]s",c);
   p=c;                /*since after reading then pointer points to another 
                       location iam using a second pointer to store the base 
                       address*/ 
   printf("%s",p);
   return 0;
 }

答案 11 :(得分:-3)

使用以下代码读取带空格的字符串:
scanf("[%s/n]",str_ptr);

相关问题