Part 3 of 5 in Reading input and writing output  

Line echo by harsha_s

Problem statement

Read a line of characters from the console and write it back

Input

A line of characters which may include spaces, punctuation marks and other special characters. The line will be terminated by a newline character and will have at most 200 characters. Sample:

H3110 w@rld!! How are you doing today?

Output

The same line of characters that you read from the console. Sample:

H3110 w@rld!! How are you doing today?

In this problem, we need the ability to read entire lines into strings and then print them out. To see how to print strings to the console, you can refer to the editorial for Hello World. To see how to store strings and read from the console generally, you can refer to the editorial for Echo. In this editorial, we will continue on from there and only talk about how we can read lines in different languages.

char line[201];
gets(line);

We can do it using 3 different techniques in C. The easiest way is to use the gets function, to which we pass the character array. The gets function reads an entire line until the newline character is encountered or there are no more characters to read.

Other options are fgets and scanf with the format string %200[^\n]c (more info here) In the scanf option, the format string specifies that we want to read at most 200 characters that are not newline (\n)

string line;
getline(cin, line);

In C++, we can use the getline function since we are using strings. Read more about this function here. In case we want to use a character array, then we need to use the cin.getline function (more info here).

Scanner input = new Scanner(System.in);
String line = input.nextLine();
System.out.print(line);

The Scanner class in Java provides us with the nextLine method that reads an entire line of characters until a newline is encountered.

string line = Console.ReadLine();
Console.Write(line);

We can use the Readline method of the Console class in C#. This reads an entire line for us.

editorial written by harsha_s

#include<iostream>
#include<string>

using namespace std;

int main()
{
    // Declare the string with enough space to read the line
    string line;
    // Read a line from the console
    getline(cin, line);
    // Print the line back to the console
    cout<<line;

    // Return 0 to indicate normal termination
    return 0;
}

featured solution by harsha_s



To try out your code



Sign in

Sign up