c - 为什么%s遇到空格字符后不打印字符串?

标签 c

#include <stdio.h>
int main()
{
char name[20];
printf("Enter name: ");
scanf("%s", name);
printf("Your name is %s.", name);
return 0;
}

输出:

输入姓名:丹尼斯·里奇 你的名字是丹尼斯。

到目前为止我还没有找到这个问题的任何具体有效理由。谁能帮帮我吗?

最佳答案

scanf只读取直到它到达空格,这就是为什么它不在第一个空格之后存储的原因,所以你的 printf功能没有故障,就是scanf这不是存储完整的字符串,在遇到第一个空格时停止。

永远不应该使用gets() ,除非他们完全知道自己在做什么,因为它没有缓冲区溢出保护,所以它在缓冲区结束后继续读取,直到找到新行或遇到EOF。您可以阅读更多相关信息 here .请检查此Why is the gets function so dangerous that it should not be used?

您应该使用 fgets() .

    #include <stdio.h>
    int main(){

           char name[20];
           printf("Enter name: ");
           fgets(name,20,stdin);
           printf("Your name is %s.", name);
            return 0;
         }

记住fgets()还会读取换行符(按 Enter 键时得到的字符),因此您应该手动删除它。

我也强烈推荐这个answer充分利用 fgets() 的潜力并避免常见的陷阱。

这个answer讲述了如何使用 scanf 读取字符串。它的内容如下:

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

How this works? When user inputs characters from standard input, they will be stored in string variable until first blank space. After that, rest of entry will remain in input stream, and wait for next scanf. Next, we have a for loop that takes char by char from input stream (till \n) and appends them to end of string variable, thus forming a complete string same as user input from keyboard.

关于c - 为什么%s遇到空格字符后不打印字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41879626/

相关文章:

c++ - 使用按位运算符的 PE 文件格式指针

c++ - 为什么将单个枚举封装在一个结构中?

c - C编程中的指针——坐标转换

c - 内联汇编 : prevent HLT from being stopped by windows

c - 从 VC++ 2008 编译器读取控制台输入 :Error

java - C 相当于 java.util.regex

将 C 更改为 MIPS 并按位或

c++ - Z3:创建具有动态已知项数的枚举类型

c++ - 按位或 int 和 char

c - 对浮点值进行四舍五入