jackley
jackley

Reputation: 11

Capitalizing letters read from a file

I'm trying to select certain chars from a file, capitalize them, and display the output. I'm having some trouble selecting the chars:

int i;
char c;
char currentChar;
char previousChar = ' ';

inp = fopen("junk.txt", "r");
if(inp == NULL){
    printf("Error opening file, quitting... \n");
    return 1;
}

c = fgetc(inp);
 while(c != EOF){
     if(isalpha(c)){
      putchar(toupper(c));
    c = fgetc(inp);

Yes, this is a homework assignment. I'm not looking for the answer, I'm just trying to understand what I'm doing wrong. It doesn't require the use of strings or arrays. The program is supposed to read the contents of a file, capitalize the first letter of each word, and print the results.

Upvotes: 0

Views: 1279

Answers (2)

alk
alk

Reputation: 70971

Regarding the various possibilities of common word delimiters I'd propose this approach:

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

int main(void)
{
  int result = EXIT_SUCCESS; /* be optimistic! :-) */

  int charCurrent = '\0'
  int charPrevious = ' ';

  while (EOF != (charCurrent = fgetc(stdin)) || (EOF == charPrevious))
  {
    if (isspace(charPrevious))
    {
      charCurrent = toupper(charCurrent);
    }

    charPrevious = fputc(charCurrent, stdout);
  }

  if ((EOF == charCurrent) && !feof(stdin))
  {
    result = EXIT_FAILURE;
    fprintf(stderr, "error getting\n");
  }

  if (EOF == charPrevious)
  {
    result = EXIT_FAILURE;
    fprintf(stderr, "error putting\n");
  }

  return result;
}

You then invoke the program:

$ ./capitaliser <infile.txt >outfile.txt

Upvotes: 0

MOHAMED
MOHAMED

Reputation: 43548

From the toupper() page of cplusplus.com :

int toupper ( int c );

Convert lowercase letter to uppercase Converts c to its uppercase equivalent if c is a lowercase letter and has an uppercase equivalent. If no such conversion is possible, the value returned is c unchanged.

So no need of the check if(isalpha(c)) for the char that yoou want to upper case

and your code could look like this

char previousChar = ' ';
while((c = fgetc(inp)) != EOF){
   if(!isalpha(previousChar))
       putchar(toupper(c));
   else
       putchar(c);
   previousChar = c;
}

According to the alk remark: If your document contains words like peer2peer then it will displayed Peer2Peer with the previous code. And if you want to displayed Peer2peer you have to change your check in this way:

char previousChar = ' ';
while((c = fgetc(inp)) != EOF){
   if(previousChar==' ' || previousChar=='\n' || previousChar=='\r' ||
      previousChar=='\t' || previousChar=='\v')
       putchar(toupper(c));
   else
       putchar(c);
   previousChar = c;
}

Upvotes: 1

Related Questions