Home

Data Input

 

Using cin

Data input in C++ is performed using the cin class. The cin class is configured with so much flexibility (in C++, we consider that it is overloaded; in reality, it is the >> operator that is overloaded) that it can retrieve any type of declared regular variable. This includes integers, characters, floating-point numbers, or arrays of characters. Here are examples of variables that the cin class can handle:

#include <iostram>

using namespace std;
using namespace System;

int main()
{
    Console::WriteLine("Enter a natural number: ";
    int Natural;
    // Retrieve an integer
    cin >> Natural;

    Console::WriteLine("Type a decimal number: ";
    float Floater;
    // Requesting a floating pointing number
    cin >> Floater;

    Console::WriteLine("Type another decimal number: ";
    double Precision;
    // Retrieving a double-precision number
    cin >> Precision;

    Console::WriteLine("Are you ready for C++ (y=Yes/n=No)? ";
    char Answer;
    // Requesting a character
    cin >> Answer;

    Console::WriteLine("\nHere is what we got from you");
    Console::Write("Natural Number: ");
    Console::WriteLine(Natural);
    Console::WriteLine("Floating Number: ");
    Console::WriteLine(Floater);
    Console::WriteLine("Double Precision: ");
    Console::WriteLine(Precision);
    
    return 0;
}
 

C How to Input Data

To request data from the user, or to retrieve it somehow, you can use scanf_s() that is part of the stdio.h file. To use it, you must provide two pieces of information. First enter the type of variable in the parentheses. Each data type is represented by a letter as follows:

 

Character Used for
c A single character
d An integer
e A floating-point number
f A floating-point number
g A floating-point number
h A short integer
i A decimal, a hexadecimal, or an octal integer
o An octal integer
s A string followed by a white space character
u An unsigned decimal integer
x A hexadecimal integer

When calling scanf_s() to retrieve a specific value, the appropriate character must be preceded by an ampersand “%” and both must be included in double-quotes. For example, to request an integer, you would write “%d”. The second piece of information is the name of the declared variable. To use scanf_s(), you can include it in a C program.

 

Previous Copyright © 2006-2016, FunctionX, Inc. Next