簡體   English   中英

C程序輸出字符會產生整數

[英]C program to output characters produces integers instead

我正在編寫一個名為split.c的程序,該程序從stdin接收一個input.txt文件作為輸入,然后將輸入文件中的所有其他單詞發送到stdoutstderr

我當前的代碼如下:

#include <stdio.h>

int main(){
  int input;

  // keep getting characters until end-of-file
  while ((input = fgetc(stdin)) != EOF){

  // prints to stdout
  fprintf(stdout, "%d", input);
  if(input == " ")
      printf("\n");   // encounters whitespace so print new line

  // prints to stderr
  fprintf(stderr, "%d", input);
  if(input == " ")
      printf("\n");   // encounters whitespace so print new line

  }

  return 0;

}

在ubuntu中,我運行make然后執行命令./split < test/input.txt > myout.txt 2> myerr.txt

預期輸出應為例如。

如果input.txt具有以下內容: "Is my code working?"

輸出應為:

myout.txt

"Is
code

myerr.txt

my
working?"

相反,我在兩個文件中都得到了以下內容:

6511032731101001051181051001179710...............

有什么想法可能是代碼有什么問題嗎? 我的思考過程錯了嗎? 這個想法是,它獲取輸入文件,讀取每個字符,然后在找到空格后,在stdout中打印新行,然后執行相同的操作,但是現在打印到stderr直到到達EOF。

我仍在學習使用stdin / out / err的輸入和輸出(雙關語:)),所以如果我編碼不正確,我也不會感到驚訝。 任何指導表示贊賞!

您正在使用%d說明符,該說明符將相應的參數解釋為數字。 您應該使用%c將相應的參數解釋為字符。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM