简体   繁体   中英

printf does not output char array in C

I have a problem with my C program not outputting the string stored in my buffer[ ] array.

My code is:

#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;
}

The first printf statement does not print, however the second one does. Please could anyone help explain why this is the case?

The problem is your with your loops, especially that while (!feof(pToFile)) loop.

Lets say your text contains a single line line less than 19 characters long, that is terminated by a newline. That last bit, the line ending in a newline is important.

What happens when you read the file is that you encounter the newline, break the inner for loop and you are back in the outer loop. Because we have not passed the end of the file yet feof(pToFile) will return false, and you go back to your for loop.

This time in the for loop the very first time you call fgetc it will notice that you are at the end of the file and return EOF and you break out of the loop. However, because your initializing expression in the for loop is index = 0 you will exit the loop with index being equal to zero.

Now the file is at its end, and feof(pToFile) will return true, and you exit the outer loop, and then you terminate the string in buffer with index being zero, ie you do

buffer[0] = '\0';

Now you have an "empty" string that you print.

The simple solution? Skip the outer while loop, you don't need it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM