gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:32:22 24 4
gpt4 key购买 nike

我编写了一段代码,用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com