C++ Tutorials


Advanced Input

Tutorials > C++ > Advanced Input

View Full Source


In the last tutorial, we learnt how to accomplish basic input. We also found that a problem existed if you had a space in your line of input. This tutorial will explain how to accept text containing a space. This is not extremely difficult to do and the tutorial is titled advanced only because it is the next step in input.

Contents of main.cpp :

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

using namespace std;

int main()
	char name[100];

	// C Section
	printf("Please enter your name : ");

Another function gets can be used to read a line from the user's keyboard. The function has the following signature :

    gets(char *);

The char * is a pointer to a character array which needs to be able to hold the characters entered by the user.

	printf("Thank you %s.\n", name);
	// C++ Section
	cout << "Please enter your name again : ";

A way of accepting an entire line of input in C++ is to use the getline method of the cout object. The signature of the method is as follows :

    cin.getline(char *, int);

The char * is a pointer to a character array which will hold the line entered by the user. The int specifies the maximum number of characters that will be taken from the input including the '\0'. A value of 100 will therefore be able to record a line consisting of 99 characters.

	cin.getline(name, 100);
	cout << "Thank you " << name << endl;


	return 0;

You should now be able to solve the problem that was found in the previous tutorial.

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

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

< Tutorial 09 - Input Tutorial 11 - Arithmetic Operators >

Back to Top

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

Read the Disclaimer