Taking User Input with C and C++

how to take an input from the user. The input could be a string or numeric type.

Last Reviewed and Updated on February 7, 2020
Posted by Parveen(Hoven),
Aptitude Trainer and Software Developer

My C/C++ Videos on Youtube

Here is the complete playlist for video lectures and tutorials for the absolute beginners. The language has been kept simple so that anybody can easily understand them. I have avoided complex jargon in these videos.

A C/C++ program can accept input from a user interactively. The input can be taken from various channels like the console window, or a file, and so on. But we shall be referring to the console input, unless otherwise stated. Both C and C++ provide different functions and objects for accepting user input. The C language takes the more intuitive approach of using a function call, whereas C++ uses a global stream object(cin) for accepting user input. The whole point is about taking input data from the user, storing it in variables of your program, and returning or displaying the processed output.

Accepting Input Using C

There are various methods of obtaining input from the user. There are many functions that can be used for this. Here is a brief summary of the possibilities.

  1. scanf
  2. _getch, and its variants like _cgets, getc, for reading single character from the console.
  3. gets
  4. fgets
  5. getline

Of the above methods the easiest to understand at this stage is the scanf function. But it has serious practical problems associated with it, so it is rarely used in a commercial application. The remaining three are difficult to understand for a beginner, who is just one chapter into C. But for your knowledge, the getline function is the most versatile and safe of all. And, fgets is better than gets because it is safer than the latter. Please also note that the getline is not a part of the standard C. The GNU C Library provides the (non-standard) getline function that makes it easy to read lines reliably.

I will explain the use only of scanf for the purposes of this tutorial. You will have to refer to the respective documentation of the other functions yourself. Please also note that the video tutorial doesn't touch upon any of the C methods for accepting user input. The tutorial discusses only the use of the C++ cin. The program below is about accepting an int number from the user. For this an int variable is created. It will receive the input from the user. The function scanf accepts a format specifier string as its first argument. And, since, we are to store an int, the correct format specifier is %d. The second argument is the address of i. The address is the location of a variable, and it can be obtained by using the address of operator against an identifier - &i - for example. scanf takes input from the user and stores it at the address you provide as the second argument.


int main()
{
    int i;
 
    scanf("%d", &i);
 
    return 0;
}

Let me explain the pitfalls of the above approach. One potential source of problem is the use of a wrong format specifier by the developer. The compiler performs no checks on that. A badly written scanf will pass through the compiler, but will never store the input into the intended variable. Such bugs can surely waste a half of your day. The second issue is the wrong input by the user. For example, the above program has no mistakes of any kind, and it will deliver the correct behaviour, provided that the user is well-behaved - who honestly and carefully enters a number, and not a string like "Hoven Trainings". If the user enters a mismatched input, the program will malfunction.

A better and recommended approach is to obtain every input from the user in the form of a string. Any conversions to int, or float, or any other type should be made after the user has entered his data. C provides a number of functions for conversion, like _atoi, for converting a string to an int number. This approach solves most of the problems, and is the one that is followed in commercial applications.

Accepting Input Using C++

The most common approach is to use the standard input: cin. The following code shows how to obtain a number input from the user.


int main()
{
    int i;
 
    cout << "Enter a number:";
 
     cin >> i;
 
    return 0;
}

The two arrows(>>) are together called the extraction operator. This operator is a binary operator that takes cin as its first operand, and the destination variable as the second. The direction of the arrows can be used to remember the direction of data flow. In our program, it is flowing from the console window towards the variable.

The possibility of a mismatched input by the user exists here also. For example, if the user enters a string instead of a number, the cin gets corrupted, and is rendered unfit for further extraction. A bad cin enters into an error state or an error condition. The most common recovery method is illustrated below.


int main()
{
    int i;
 
    cout << "Enter a number:";
 
    cin >> i;
 
    if(cin.fail())
    {
        cout << "cin corrupted" << endl;
 
        // clear the error
        cin.clear();
 
        // discard the "bad" input
        cin.ignore();
 
        // ask the user again
        cout << "Enter a number:";
 
        cin >> i;
 
        cout << i << endl;
    }
 
    return 0;
}

The above code calls fail() to determine the health of cin. If the function returns true, then cin is corrupted, and two more functions, cin.clear(), and cin.ignore() have to be called to discard and remove the bad input, and also to clear away the error flag. The function, cin.clear(), removes any error flags from the cin object, so that it is ready again.

It is possible to obtain a string input very easily using C++. Instead of using int, float, etc., for the input, it is better to use a string. A string can store any type of data, and conversions can be done after the user has entered the data. The Standard C++ allows us to use the getline function to obtain string input from the user.


#include <iostream>
#include <string>

using namespace std;

int main()
{
    string str;

    cout << "Enter your name: ";

    getline(cin, str);

    cout << "You entered " << str << endl;

    return 0;
}


 

Classroom Training

Classroom training in C/C++ is available at our training institute. Click here for details. You can also register yourself here.

Video Tutorial

We have created a video tutorial that can be downloaded and watched offline on your windows based computer. It is in the form of an exe file. No installation is required, it runs by double clicking the file. Since the exe file is hosted on the Google Drive, it should be very safe because Google itself checks for any virus or malware. The video can be watched offline, no internet is required.

Pricing

This single video will cost you USD $5. When you download the video, you will be able to watch the first few minutes for free, as a sample. The video app will prompt you for payment through PayPal and other payment options. If you want ALL VIDEOS, NOT JUST THIS ONE then go here: Complete Set of C/C++ Video Tutorials The entire set is priced at USD $50.

Screenshots

This is a screenshot of the software that should give you a good idea of the available functionality. Click on the image to see a larger view.screenshot of the video being played in the software

Installation

This software doesn't require any installation. Just download and double-click to run it. It doesn't require administrative priviliges to run. It runs in limited access mode, so should be very safe.

supports windows xp and later Supported Operating Systems

These videos can be run on 32-bit as well as 64-bit versions of the Microsoft Windows Operating Systems. Windows XP and all later OS are supported. If you want to run it on Windows XP and Windows Vista, then you must also have the .NET Framework Version 3.5 installed on your machines. Those users who have Windows 7 and later donot have to worry because these operating systems already have the .NET Framework installed on them.

Download Links

IMPORTANT NOTE: This download contains ONLY ONE video. The video is about the topic of this tutorial.

Want ALL Videos? If you want ALL VIDEOS, NOT JUST THIS ONE then go here: Complete Set of C/C++ Video Tutorials. TIP: If you plan to buy these videos, then it would be more economical to buy the entire set.

DISCLAIMER: Even though every care has been taken in making this software bug-free, but still please take a proper backup of your PC data before you use it. We shall not be responsible for any damages or consequential damages arising out of the use of this software. Please use it solely at your own risk.

Please download the software here.
download the video Taking User Input with C++



Creative Commons License
This Blog Post/Article "Taking User Input with C and C++" by Parveen (Hoven) is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
Updated on 2020-02-07. Published on: 2015-10-05