Ravinder Singh

Male
Friday, February 24, 1984
I am a software engineer by profession and programmer by passion. I love working on software projects which help make a positive impact on the society.

How to read a multiline input from console window using C programming

Category: Programming In C Date: Thursday, December 22, 2016

In this program we have used an infinite loop to read string input from the user. The string input from the user is read into a string array strinput. If the user presses enter without entering any text, the length of the input comes out to be zero and we break out of the loop. Otherwise we store the string input into a bigger array by the name allText.

#include <stdio.h>
#include<string.h>

int main()
{
    char *strinput = (char *)malloc(100);
    char *allText = (char *)malloc(500);

    int totalCharacterCount = 0;

    int count = 0;

    while(true)
    {
        gets(strinput);

        count = strlen(strinput);
        if(count==0)
            break;

        while(*strinput!='\0')
            {
                allText[totalCharacterCount] = *strinput;
                strinput++;
                totalCharacterCount++;
            }

            allText[totalCharacterCount] = '\n';
            totalCharacterCount++;
    }

    printf("%s",allText);

    return 0;
}

Notice that after the while loop where we transfer the string input from strinput to allText we are adding a newline character into allText. This is being done because when the user finishes entering the first lines and goes to the next line, we do not receive the input as a newline from the console window. We add a newline character by ourself so that the final input can be seen exactly in the format in which it was entered by the user.

Below you can see the output of this program

Image

 

 

Rate this article and help us improve

Please Login to rate
Overall ratings: 0 | Rating: out of 5
Previous Article Next Article

Quick Links

E-Magazines

@

Total Followers
Study Group Created
Study Group Joined
Following Teacher
Following Organization
Blog Articles Added
Questions Asked
Questions Answered
Jobs Posted
Total Members in Group
Questions asked by members
Tasks added in this Group

Please wait..

Ok

Login to Open ESchool OR Create your account    Login   SignUp