c - 为什么 fgets() 不接受 C 程序中的输入?

标签 c fgets

我编写了一段代码,用 C 实现 Julias Caesar 密码学。
问题是我的fgets()没有等待输入并且跳到fputs()

#include<stdio.h>
int main(){
    int size;
    printf("Enter the size of the string: ");
    scanf("%d",&size);

    int key;
    printf("Enter the key: ");
    scanf("%d",&key);

    char a[size];
    printf("Enter the string: ");
    fgets(a,size,stdin);

    for(int i=0;i<size;i++){
        a[i]+=key;
    }

    fputs(a,stdout);
    return 0;
}

我使用CodeBlocks 17.12来编译这个C程序。
我的操作系统是 Windows 7(32 位)

最佳答案

欢迎来到 stackoverflow。

当您输入答案时,缓冲区末尾有一个换行符 (\n)。当 fgets() 读取您的输入时,它会读取换行符。您可以删除换行符,或者使用正则表达式来跳过它,或者使用 fgets() 一次,以便您可以按照 this other answer 中的建议再次使用 scanf() 。这可能对你有帮助。

并且,请记住在发布问题之前先在 stackoverflow 中进行搜索!

关于c - 为什么 fgets() 不接受 C 程序中的输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59844800/

相关文章:

c - 如何使用C逐行读取txt文件(int,未知长度)?

C 结构不扫描所有输入

C 第一个 fgets() 在第二个运行时被跳过

c - 从函数中替换 char[] 中的字符

c - 无符号字符的 v8 Node 缓冲区

c - c指针问题

C - fgets 奇怪的行为

c - 如何在套接字编程c中从telnet客户端读取服务器上的参数

c - 为多条消息重用一个管道

c - fgets 和 printf 的问题..打印字符串