c - 程序跳过输入和退出步骤
问题描述
#include<unistd.h>
#include<stdio.h>
#include<string.h>
#include<fcntl.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<stdlib.h>
int main()
{
int fd1;
char * myfifo = "/home/karthik/code/test.txt";
mkfifo(myfifo, 0666);
char str1[80],str2[80],Conformation_Flag;
//Shows what's in file.
fd1 = open(myfifo,O_RDONLY);
read(fd1,str1,80);
printf("Text : %s",str1);
close(fd1);
printf("Edit? (y/n) : ");
scanf("%c",&Conformation_Flag);
if(Conformation_Flag == 'y')
{
printf("Enter the text : ");
fflush(stdin);
//Take input and write to file.
fd1 = open(myfifo,O_WRONLY);
fgets(str2,80,stdin);
write(fd1,str2 ,strlen(str2)+1);
close(fd1);
}
else if(Conformation_Flag == 'n')
{
exit(0);
}
else
{
printf("Invalid Option!");
}
return 0;
}
我期待这样的输出:
文本:虚拟文本
编辑?(是/否):是
输入文本:再次虚拟文本
按回车后程序应该退出。
但我得到这样的输出:
文本:虚拟文本
编辑?(是/否):是
程序退出而不接受输入。
在 wsl(Debian 10) 和 gcc (Debian 8.3.0-6) 8.3.0 上编译
并尝试在 "%c "[ scanf("%c ",&Conformation_Flag); ] 但在输入后它没有关闭
代码中有什么磨损
解决方案
正如第一条评论所暗示的,新行留在标准输入中,并在下一个标准输入读取操作中读取。
作为一个骇人听闻的解决方案,请使用以下内容:
//scanf("%c",&Conformation_Flag);
Conformation_Flag = fgetc(stdin); //reads the y or n
fgetc(stdin); // reads a new line
这是一个变体getline()
作为替代。例如基于如何使用 C 从键盘读取字符串?
char *line = NULL; /* forces getline to allocate with malloc */
size_t len = 0; /* ignored when line = NULL */
int read_n = 0;
read_n = getline(&line, &len, stdin);
Conformation_Flag = line[0];
free(line);
推荐阅读
- c++ - 您如何将结构作为类中的私有成员并为其创建参数化的构造函数/设置器函数?
- yaml - 第 10 行的 yaml 语法有错误
- javascript - 未处理的拒绝 (TypeError):state.cartItems 未定义
- mysql - 在 SQL 中使用 AND 和括号分组不起作用
- python - 在这种情况下如何滚动带有背景的元素?
- python - 如何使用 for 循环创建许多无线电输入?
- flutter - Flutter/Dart中这种选择叫什么名字?
- php - 如何在 docker 中将这些设置添加到我的 php.ini
- c# - C# 如何将 JSON 插入 Google BigQuery 表架构
- assembly - TAS 指令 68000