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?
while(!feof(pToFile))is wrongprintfcalled? Is the output of that what it should be? What is the input (the file)? And please read Why is “while ( !feof (file) )” always wrong?.indexback to0. When you finally readEOFafter the last newline,index = 0, so you dobuffer[0] = '\0';, so there's nothing to print.printfwill only print something if the file doesn't end with a newline. Then it will print that last line.