繁体   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