Dev C++ Entering User Inputs

This tutorial will teach you how to take input from a user in C# using the Console.ReadLine method. When writing a computer program, you will often rely on a user interacting with your program. For example, your program may ask the user a question, wait for a response, and then do something with the information the user provides. C uses a convenient abstraction called streamsto perform input and output operations in sequential media such as the screen, the keyboard or a file. A streamis an entity where a program can either insert or extract characters to/from. There is no need to know details about the media associated to the stream or any of its internal specifications.

C++ user input array
  • C++ Basics
  • C++ Object Oriented
  • C++ Advanced
  • C++ Useful Resources
  • Selected Reading

The C++ standard libraries provide an extensive set of input/output capabilities which we will see in subsequent chapters. This chapter will discuss very basic and most common I/O operations required for C++ programming.

C++ I/O occurs in streams, which are sequences of bytes. If bytes flow from a device like a keyboard, a disk drive, or a network connection etc. to main memory, this is called input operation and if bytes flow from main memory to a device like a display screen, a printer, a disk drive, or a network connection, etc., this is called output operation.

I/O Library Header Files

There are following header files important to C++ programs −

Sr.NoHeader File & Function and Description
1

<iostream>

This file defines the cin, cout, cerr and clog objects, which correspond to the standard input stream, the standard output stream, the un-buffered standard error stream and the buffered standard error stream, respectively.

2

<iomanip>

This file declares services useful for performing formatted I/O with so-called parameterized stream manipulators, such as setw and setprecision.

3

<fstream>

This file declares services for user-controlled file processing. We will discuss about it in detail in File and Stream related chapter.

The Standard Output Stream (cout)

The predefined object cout is an instance of ostream class. The cout object is said to be 'connected to' the standard output device, which usually is the display screen. The cout is used in conjunction with the stream insertion operator, which is written as << which are two less than signs as shown in the following example.

When the above code is compiled and executed, it produces the following result −

The C++ compiler also determines the data type of variable to be output and selects the appropriate stream insertion operator to display the value. The << operator is overloaded to output data items of built-in types integer, float, double, strings and pointer values.

The insertion operator << may be used more than once in a single statement as shown above and endl is used to add a new-line at the end of the line.

The Standard Input Stream (cin)

The predefined object cin is an instance of istream class. The cin object is said to be attached to the standard input device, which usually is the keyboard. The cin is used in conjunction with the stream extraction operator, which is written as >> which are two greater than signs as shown in the following example.

When the above code is compiled and executed, it will prompt you to enter a name. You enter a value and then hit enter to see the following result −

The C++ compiler also determines the data type of the entered value and selects the appropriate stream extraction operator to extract the value and store it in the given variables.

The stream extraction operator >> may be used more than once in a single statement. To request more than one datum you can use the following −

This will be equivalent to the following two statements −

The Standard Error Stream (cerr)

The predefined object cerr is an instance of ostream class. The cerr object is said to be attached to the standard error device, which is also a display screen but the object cerr is un-buffered and each stream insertion to cerr causes its output to appear immediately.

C++ Validating User Input

The cerr is also used in conjunction with the stream insertion operator as shown in the following example.

When the above code is compiled and executed, it produces the following result −

The Standard Log Stream (clog)

The predefined object clog is an instance of ostream class. The clog object is said to be attached to the standard error device, which is also a display screen but the object clog is buffered. This means that each insertion to clog could cause its output to be held in a buffer until the buffer is filled or until the buffer is flushed.

The clog is also used in conjunction with the stream insertion operator as shown in the following example.

When the above code is compiled and executed, it produces the following result −

You would not be able to see any difference in cout, cerr and clog with these small examples, but while writing and executing big programs the difference becomes obvious. So it is good practice to display error messages using cerr stream and while displaying other log messages then clog should be used.

This guide is part of a series. For more lessons, visit the C# for Beginners tutorial.

This tutorial will teach you how to take input from a user in C# using the Console.ReadLine() method. When writing a computer program, you will often rely on a user interacting with your program. For example, your program may ask the user a question, wait for a response, and then do something with the information the user provides. Creating these types of dynamic user interactions becomes increasingly important as we write more complex programs in C#.

That is precisely the type of program we will be writing in this example.

C# Console.ReadLine() Example

In this example, we will write a .NET Core console application that gathers information from an end user and then we will process that data and print some results to the screen. Start by creating a new Project (File > New > Project…) and select the .NET Core Console App template. You can call the project UserInteraction.

You will be shown a boilerplate template that you are, by now, familiar with. This example will incorporate several features from our previous tutorials. Recall in our first C# program, we called the Console.ReadLine() method to force our console application to wait for user input and prevent the terminal window from immediately closing after our code was executed. In this example, that same method will serve as the basis for our user interaction.

In the previous lesson, we learned about different data types and how to declare variables. In this example, we will be using variables of type Integer and String.

Let’s get started by adding the following lines to your Main() method:

You will notice in Line 10, we use Console.Write() instead of Console.WriteLine(). The difference between the two methods is that the .WriteLine() method of the Console class appends a new line character after the string, forcing the cursor to move to the next line. The Write() method, on the other hand, will print a string and leave the cursor at the end of the line, without moving to a new line.

Now we will declare a string variable and use it to capture the user’s input. Add the highlighted lines to your code:

In line 12, we declared a string variable called myFirstName. Then, in line 13, we used the assignment operator ( = ) to assign a value to that variable. We want myFirstName to have the value of whatever the user types in the console. When the user types his name and presses the Enter key, the name is saved to the variable myFirstName and can be used elsewhere in your program.

Let’s get some more information from the user. Let’s ask for the user’s last name. What type of variable should we use?

We use another String variable to save the user’s last name. Notice on Line 16, we declare a variable and assign a value all on one line. This is a shorter way to do what took us two lines in lines 12-13. It is good practice to assign a value to a variable as soon as possible after we declare it. Moreover, our code is shorter and easier to read when we organize it this way.

Getting an Integer from Console.ReadLine()

Next, let’s ask the user for the year he/she was born. We will want to store that value in a new valuable, and make some calculations with it in order to determine the person’s age. What variable data type do you think we should use?

If we only wanted to show the value somewhere else in our application, we could just use a String like we did when we were taking the user’s name. However, we will be performing mathematical calculations, and we can’t do that on Strings. We need to store the value as some type of number. A birth year, like 1980, is a whole number value, so we can declare an Integer variable. I will use the tip we learned earlier to declare a variable and assign it a value on one line (Line 19).

Observe that we have added some special code, Convert.ToInt32(), in order to save the value of Console.ReadLine() to an Integer data type. Console.ReadLine() expects a sequence of alphanumeric Unicode characters, a String. We can’t assign a String to an Integer variable. The data types don’t match. We will use the ToInt32() method of the Convert class in order to parse our String as an Integer. With this method, we can convert an alphanumeric string into a whole number and be able to use it to make calculations in our program.

Note: In a real application, we would want to include some error checking to ensure that the value entered is actually a number before we try to convert it.

A Complete Console.ReadLine() Example

Until now, we have simply saved the user’s input to a variable, but we haven’t actually done anything with that data. To finish our program, we will want to present some content to the end user based on the data they have provided.

Max for live 6.1 crack. On Line 21, we are simply inserting a blank line into the console to provide some spacing between the questions we have asked and the output we are about to display. On Line 22, we are joining our strings together with the Concatenation Operation ( + ). Notice, we can write a string inside double quotes like we have been doing, but we can also reference our existing string variables by their name. Since these variables were assigned values based on the user’s input, their first and last name will appear in our console application.

On Line 24, we calculate the user’s age based on the year they were born. We do this by subtracting the user’s birthyear, a value the user provided, from the current year which we retrieve using DateTime.Now.Year. There are a lot of interesting things we can do with a DateTime variable, so that will be a separate tutorial of its own! For now, it is sufficient to say that DateTime.Now fetches the current local date and time, and Year is a property of the DateTime structure that gets the year represented by our DateTime instance.

On Line 27, we make another calculation with an Integer variable. This time, we want to tell the user how old they will be in five years. We will use the age we just computed on Line 24, and simply add 5 to that value. Finally, we write this to the console and our application is complete. If you run your interactive program, you should see something like the following:

The Bottom Line

In this tutorial, we learned how we can use the Console.ReadLine() method to capture a user’s input. We learned how to save those values as String variables in order to retrieve them later in our program. We learned that Console.ReadLine() returns a String, so if we want to save that String as a number, we have to make a conversion. Once we have the variable saved as an Integer data type, we can retrieve it to make calculations.

What useful ideas do you have for the Console.ReadLine() method? Let me know in the comments! As always, if you have any questions, let me know below.

Scroll back to top

Looking for more?

You have visited our site before, and we appreciate you!

If you found the tutorials helpful, enter your email address for more free C# tips and tricks.

No, thank you

Dev C++ Entering User Inputs Permissions

Map

Can't get enough C#?

Enter your email address for more free C# tutorials and tips.

No, thank you