Home »
C++ programming language
How to read a string with spaces in C++?
In this chapter, we will learn how to read a complete string with spaces in C++?
Read a string with spaces in C++
To read any kind of value like integer, float, character we use cin, cin is the object of istream class that tells to the compiler to read value from the input device.
But, in case of string cin does not work properly.
Example to to read a string with spaces
Let's read a string using cin
#include <iostream>
using namespace std;
int main()
{
char name[100]={0};
//read name
cout<<"Enter your name: ";
cin>>name;
//print name
cout<<"Name is: "<<name<<endl;
return 0;
}
Now, consider the output -1. Here, I am giving "Vanka" (A name without space).
Output - 1
Enter your name: Vanka
Name is: Vanka
"Vanka" will be stored into variable name and print successfully.
Now, consider the output -2. Here, I am giving "Vanka Manikanth" (A name with space).
Output - 2
Enter your name: Vanka Manikanth
Name is: Vanka
In this case, string will be terminated as spaces found, this only "Vanka" will be stored in variable name.
Read string with spaces in C++
We can use a function getline(), that enable to read string until enter (return key) not found.
Reading string using cin.getline() with spaces
getline() is the member fucntion of istream class, which is used to read string with spaces, here are the following parameters of getline() function [Read more about std::istream::getline]
Syntax:
istream& getline (char* s, streamsize n );
char*s: character pointer (string) to store the string
streamsize n: maximum number of characters to read a string
Example to read string using cin.getline() with spaces
Consider the given program
#include <iostream>
using namespace std;
int main()
{
char name[100]={0};
//read name
cout<<"Enter your name: ";
cin.getline(name,100);
//print name
cout<<"Name is: "<<name<<endl;
return 0;
}
Consider the given output; here I am giving "Mr. Vanka Manikanth" (A name that contains two spaces between the words).
Output
Enter your name: Mr. Vanka Manikanth
Name is: Mr. Vanka Manikanth
Here, complete name/string "Mr. Vanka Manikanth" will be stored in variable name.