【问题标题】:line splitter from stdout to stdin从标准输出到标准输入的分线器
【发布时间】:2015-03-16 15:36:42
【问题描述】:

我是 C 编程的新手,我被要求构建一个简单的行拆分器, 它接收来自用户的句子输入(在标准输入中),并在标准输出中再次打印(不保存整个句子),如果输入了“@”或“*”,则跳过一行(“\n”)。 (他们还希望每个句子都以其行号开头)。 我完成了这个程序,它工作得很好,除了一件小事: 对于我尝试的每个输入,第一个字母都会丢失。 其余的按我的要求完成。

谁能告诉我怎么了?

#include <stdlib.h>
#include <stdio.h>
#include <string.h>


int main(int argc, char **argv) {
    char cInput;
    int i = 1;
    int moreData = 1;

    printf( "line_splitter, please enter a sentence:\n");
    fflush(stdout); 
    cInput = fgetc(stdin);
    printf("%c: ", i);
    i=i+1;


/*while not end of file read to avoid error*/   
    while(!feof(stdin) && moreData){
    cInput = fgetc(stdin);
    fputc(cInput,stdout);
    switch(cInput){
        case '@':
        case '*':
            printf("\n");
            printf("%d: ", i);
            i=i+1;
        break;
        case '\n':
            moreData = 0;
        default:
            break;
    }
     }
     printf( "\ndone!\n");

  return 0; 
}

编辑: 谢谢大家,我做到了:)

【问题讨论】:

  • 您的意思是在第二个printf 中使用%d 而不是%c
  • 是的,它用于行数,而不是用于接收的输入
  • default:break; 不需要删除它。

标签: c stdout stdin


【解决方案1】:

在您使用fflush 之后,您会立即读取一个字符。该字符永远不会被打印/处理。删除该读取,然后将您的 while 循环更新为

while((cInput = fgetc(stdin)) != EOF && moreData)

确保将 cInput 重新声明为 int,这是 fgetc 的正确返回类型。

【讨论】:

  • 并删除while循环中的fgetc
  • 你说的 while 循环改变了,但是当我把 cInput 改成 int 时,它并没有像它应该的那样打印我的句子 =/
  • 我尝试了相同的更改并且成功了。我唯一的问题是我必须修复上面提到的 CG 的 printf 并且“1:”过早出现在屏幕上。
猜你喜欢
  • 1970-01-01
  • 2013-09-18
  • 1970-01-01
  • 1970-01-01
  • 2021-12-13
  • 2014-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多