簡體   English   中英

printf在C中不輸出char數組

[英]printf does not output char array in C

我的C程序無法輸出存儲在buffer[ ]數組中的字符串,這是一個問題。

我的代碼是:

#include <stdio.h>
#include <ctype.h>

int main()
{
  int textSize = 20;

  int index, ch;
  int count = 0;
  int upperCount = 0;
  int lowerCount = 0;
  char buffer[textSize];

  FILE *pToFile = fopen("input.txt", "r");   

  if (pToFile != NULL)
  {
    while (!feof(pToFile))
    {    
      /* Read in a single line from "stdin": */
      for(index = 0; (index < textSize) && ((ch = fgetc(pToFile)) != EOF)
                      && (ch != '\n'); index++) {
        if(islower(ch))
        {
          buffer[index] = toupper(ch);
          count++;
          upperCount++;
        }
        else if(isupper(ch))
        {
          buffer[index] = tolower(ch);
          count++;
          lowerCount++;
        }
        else
        {
          buffer[index] = (char)ch;
          count++;
        }
      }
    }
  }
  fclose(pToFile);      

  /* Terminate string with null characters: */
  buffer[index] = '\0';

  /* Print output out onto screen */
  printf("%s\n", buffer);
  printf("Read %d characters in total, %d converted to upper-case, %d to lower-case\n", 
                             count, upperCount, lowerCount);
  return 0;
}

第一個printf語句不打印,但是第二個打印。 請任何人幫助解釋為什么會這樣嗎?

問題出在您的循環中,尤其是while (!feof(pToFile))循環時。

假設您的文字包含一行少於19個字符的單行,並以換行符結尾。 最后一點,以換行符結尾的行很重要。

讀取文件時發生的情況是遇到換行符,中斷了內部for循環,而您又回到了外部循環中。 因為我們尚未傳遞文件的末尾,但feof(pToFile)將返回false,然后返回到for循環。

這次在for循環中,第一次調用fgetc它會注意到您位於文件末尾並返回EOF並且退出循環。 但是,由於您在for循環中的初始化表達式是index = 0您將退出index等於零的循環。

現在文件在其末尾, feof(pToFile)將返回true,退出外部循環,然后在index為零的緩沖區中終止字符串,即

buffer[0] = '\0';

現在,您有一個“空”字符串要打印。

簡單的解決方案? 跳過外部的while循環,則不需要它。

暫無
暫無

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

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