Question 3

Question: Write a program that capitalizes the first letter of each word from a input string
Answer: 

#include <stdio.h>
#include <ctype.h>                               /*The ctype.h header file of the C Standard Library provides                                                                                                             declares several functions useful for testing and mapping characters. */
int main(void){
    int c;
    int alreadyUp = 1;  /*Check if the previous character is capitalized or not*/
                        /*Assume that: 1 is not uppercase yet and 2 is already uppercase*/

    /*Create an infinite loop*/
    for( ; ; ){
        c = getchar();
        if(c == EOF) break;

        switch (alreadyUp){
        case 1:
            if(isalpha(c)){                 /*if c is alpha and not uppercase yet*/
                putchar(toupper(c));
                alreadyUp = 2;              /*set the contraint to be 2 which is already uppercase*/
            } else putchar(c);              /*blank space ONLY*/
            break;
        case 2:
            if(!isalpha(c)){
                putchar(c);
                alreadyUp = 1;
            } else putchar(c);
            break;
        default:
            printf("This should not be showed in the result");
        }
    }
    return 0;
}


Output:


No Response to "Question 3"

Post a Comment

 

Copyright © 2013-2014 Lai Duy Thanh All rights reserved.