Wednesday, June 10, 2015

C program to input string and count the characters


The C program given below is able to get input string type data from user. For example: you can input a word or a line. After running the program, first of all a message will appear asking to provide string type data.

If you input something like I am a good boy. then that line will be stored into an array by the gets() function. And soon the length will be counted by the strlen() function and the number of characters will be stored into an integer type variable length.

Remember the program will count the number of characters including spaces, punctuation, special symbols and all others. We have to count the number of characters because later we will print that line or word using a for-loop.

But, we can also print that line using the puts() function simply. Then we have to replace 25th to 28th number line by a single line puts(msg);
/*----------------------------
|C program to input a sentence|
-----------------------------*/
#include <stdio.h>
#include <string.h>
int main(){
    //declaring an integer variable
    int i;

    //declaring an character type arraye
    char msg[100];

    //message to enter the sentencei
    printf("Enter a sentence: ");

    //getting data into msg array
    gets(msg);

    //defining the number of character
    int length = strlen(msg);

    //Displaying the number of character
    printf("There are %d characters!!\n",length);

    //for-loop to display the data
    for(i=0; i<=length; i++){
        printf("%c",msg[i]);
    }
}


Advertisement

No comments:

Post a Comment