Search code examples
cfile-ioletters

capitalize first letter in file


I'm trying to capitalize first letter. The chars are read from text file. Unfortunately, I can't. I read an idea it says add two boolean variables, which could be of type int: one variable will hold 1 when the current character is part of a word, the other variable will hold 1 when the previous character is part of a word. But, how can I know whether char is part of word or not ?

#include <stdio.h>

void cpt(char x[]);

int main(){

    cptlz("in.txt");

    return 0;
}
void cptlz(char x[]){

    char ch;

    int currentch,
        previouschar,
        st=1;

    FILE *fptr_in;

    if((fptr_in=fopen(x,"r"))==NULL){
        printf("Error reading file\n");
    }
    else{
        while(st==1){
            st=fscanf(fptr_in,"%c",&ch);
        if (ch >= 'a' && ch <= 'z'){
            printf("%c",ch-32);
        }
            else
                printf("%c",ch);
            }
        }
}

Solution

  • Just try this code..

    void cptlz(char x[]){
    
    char ch;
    
    int currentch,
        previouschar='\n',
        st=1;
    
    FILE *fptr_in;
    
    if((fptr_in=fopen(x,"r"))==NULL){
        printf("Error reading file\n");
    }
    else{
    
        while((ch=fgetc(fptr_in))!=EOF){
    
        if (ch >= 'a' && ch <= 'z' && (previouschar=='\n' || previouschar==' ')){
            printf("%c",ch-32);
        }
            else
                printf("%c",ch);
    
        previouschar=ch;
            }
    
        }
    }