c - While 循环不能与 fgetc 一起使用

标签 c string while-loop fifo fgetc

这就是我正在尝试做的事情:

  1. 我要求用户输入一些句子

  2. 每当他想停止时,他就会按 Q(大写字母)

  3. 然后应该开始下一个处理。

我现在得到的:

  1. 系统会提示用户输入任意数量的句子
  2. 但是当他按 Q 时,控件不会从 while 循环转移到下一条指令。

这是一个 FIFO 程序。如果您发现任何其他错误,请报告它们。谢谢!

代码如下:

#include<stdio.h>
#include<fcntl.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/stat.h>
void main()
{

int i=0,fd;
char str[500]="",ch;

char *myfifo="/home/rahulp/Desktop/myfifo";

mkfifo(myfifo,0666);    

printf("Enter the sentences:");

while((ch=fgetc(stdin))!='Q')
{
    printf("ch===%c",ch);
    str[i++]=ch;

}
str[i]='\0';

fd=open(myfifo,O_WRONLY);

if(fd<0)
{
    printf("Cannot open fifo");
}
else
{
    write(fd,str,strlen(str));
}

close(fd);
unlink(myfifo); 
}

最佳答案

忽略 mkfifo 发生问题的可能性,这就是您应该如何读取 stdin:

int ch;

printf("Enter the sentences:");
fflush(stdout);

while ((ch = fgetc(stdin)) != EOF)
{
    if (ch == 'Q')
        break;
    printf("ch=%c\n", ch);
    str[i++]=ch;
}
str[i]='\0';

关于c - While 循环不能与 fgetc 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36459462/

相关文章:

C - while 和 for 循环的奇怪行为

C 指针值 - LHS 值发生意外变化

c - sk_buff 复制 & sk_buff 克隆

c - 在 pow() 中执行双数组时输出错误

C - 如何解析具有特定格式的文件(或字符串)

JavaScript "firstNonRepeatingLetter"函数返回未定义而不是字符?

Scheme 中的递归(或 while 循环)

android - 使用 GZIPOutputStream 压缩字符串

c - 使用指针从字符串中删除空格

python - 有没有办法让一个循环在后台运行,而其他代码继续在 python 中运行?