how to store full name in C++

In the program given here, we will discuss How to store a full name in C++?.

In the previous state we used default input class cin to read a data but its not able to read space and a full name always contain space between first name and last name, In this situation we used C++ library function to solve this Problem.

Let’s discuss here,

In this program, we will ask the user to input two names. Both names are stored differently in the program.

Here is the program,

#include<iostream>
#include<stdio>    // for gets() function
using namespace std;

int main()
{
   char name1[20],name2[20];  // declaration of variable name1,and name2;

   cout<<"Enter Name: "; 
   cin>>name1;

   cout<<"Enter Name: ";
   gets(name2);

     // print values of these variables
   cout<<"Name: "<<name1;
   cout<<"Name: "<<name2;

return 0;
}

OUTPUT

 Enter name: Rahul_sherma 
 Enter name: Rahul sherma

 Name: Rahul_sherma
 Name: Rahul sherma

Explanation

Two variable name1 and name2 have been declared in the program. In which the name entered by the user will be stored.

suppose both given name is rahul sherm, so

name1 = rahul sherma
name2 = rahul sherma

But here the variable name1 is used with the cin statement,

cin>>name1;

and because, the cin statement does not read the space. Therefore, variable name1 will only store Rahul,

While variable name2 is used with gets() functon,

gets(name2);

so variable name will store the complete name(with space).

such as,

Remember, where we have to include the header file iostream in the program to use the cin statement. To use the gets() function, we have to include its header file stdio in the program.

Instead of the gets() function we can also use the getline() function.

We will discuss these functions in string


C++ Examples

Like it?
Exit mobile version