gpt4 book ai didi

c - 想要在c中的文件中插入多个字符(一次一个)

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

我一直在尝试输入字符,并且该字符应该放入文件中,除非用户将 opt 的值更改为“n”。

#include<stdio.h>
void main()
{
char ch,opt='y';
FILE *fp;
fp=fopen("myfile.txt","w");
while(opt=='y' || opt =='Y')
{ scanf("%c",&ch);
fputc(ch,fp);
printf("want to enter more characters(y or n):");
scanf("%c",&opt);
}
fclose(fp);
}

所以我想提供输入,直到 opt 值更改为“n”。

最佳答案

如果您使用的是Windows操作系统,那么您可以使用以下代码来读取字符,而无需按Enter。请参阅herehere了解如何在 Linux 平台上不按 Enter 读取字符。

#include<stdio.h>
#include<conio.h>

void main()
{
char ch,opt='y';
FILE *fp;
fp=fopen("myfile.txt","w");
while(opt=='y' || opt =='Y')
{
ch = getch();
fputc(ch,fp);
printf("%c\nWant to enter more characters(y or n):", ch);
opt = getch();
printf("%c\n", opt);
}
fclose(fp);
}

注意:如果不需要打印最后输入的字符,可以修改代码。请参阅here了解 getch() 函数的其他变体。

关于c - 想要在c中的文件中插入多个字符(一次一个),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48982059/

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