首页 > 解决方案 > 程序跳过输入和退出步骤

问题描述

#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); ] 但在输入后它没有关闭

代码中有什么磨损

标签: cdata-structures

解决方案


正如第一条评论所暗示的,新行留在标准输入中,并在下一个标准输入读取操作中读取。

作为一个骇人听闻的解决方案,请使用以下内容:

    //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);

推荐阅读