C++ Tutorials



Tutorials > C++ > Input

View Full Source


We have been dealing a lot with outputting information to the console. You may find the need to record user input. This will be discussed in this tutorial. Input can be accomplished by using the scanf function for C or the cin object for C++.

Contents of main.cpp :

#include <stdio.h>
#include <stdlib.h>
#include <iostream>

using namespace std;

int main()

The name array will be used to store input as a string and the age variable will be used to store integers. You need to give the string sufficient space to accept the input. The program in this case will therefore not accept input greater than 50 characters.

	char name[50];
	int age = 0;

The scanf function takes parameters as follows :

    scanf(const char *format, arguments...)

The arguments are the variables that will be used to store the input. The format follows the same specifications as the printf statement.

	// C Section
	printf("Please enter your first name : ");
	scanf("%s", name);

	printf("Please enter your age : ");
	scanf("%d", &age);

	printf("Thank you %s. You are %d years old.\n",
		name, age);

The cin object is used the same way as the cout object but instead of using the << operator, you use the >> operator.
An easy way to remember which operator to use is to say that the arrows point to where data is being transmitted to.

	// C++ Section
	cout << "Please enter your first name : ";
	cin >> name;
	cout << "Please enter your age : ";
	cin >> age;

	cout << "Thank you " << name
		<< ". You are " << age
		<< " years old." << endl;


	return 0;

Congratulations. You should now be able to accomplish basic input. You may notice that if you type in a string containing a space, an error may occur. If you type in eg. "Bob 52", you will enter information for both fields.
We will find out how to accept input with a space in a later tutorial.

Please let me know of any comments you may have : Contact Me

Source Files : Visual Studio Dev-C++ Unix / Linux

< Tutorial 08 - Pointers Tutorial 10 - Advanced Input >

Back to Top

All Rights Reserved, © Zeus Communication, Multimedia & Development 2004-2005

Read the Disclaimer