【问题标题】:Program skipping the step of taking input and exiting程序跳过输入和退出步骤
【发布时间】:2020-03-22 21:37:27
【问题描述】:
#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",&amp;Conformation_Flag); 在输入缓冲区中留下一个换行符,第一个 fgets 将其作为空行拾取。另外,最好使用面向流的文件打开功能fopen
  • 您需要在第一个read 之后为str1 添加一个空终止符。你不应该使用printf("%s") 来打印一个可能没有正确地以空值终止的缓冲区。

标签: c data-structures


【解决方案1】:

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

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

    //scanf("%c",&Conformation_Flag);
    Conformation_Flag = fgetc(stdin); //reads the y or n
    fgetc(stdin); // reads a new line

这里有一个变体,用getline() 作为替代。例如。基于How to read string from keyboard using 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);

【讨论】:

    猜你喜欢
    • 2019-06-19
    • 1970-01-01
    • 1970-01-01
    • 2015-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多