Home » C++ programs » C++ Most popular & searched programs

C++ program to read a string

Here, we will learn how to read string with/without spaces using cin and cin.getline() in C++? Here, we are writing two programs, first program will read a string using cin (without spaces) and second proram will read a string with spaces using cin.getline().

Program to read a string using cin in C++



#include <iostream>
using namespace std;

int main()
{
	//declaring string (character array)
	char text[100]={0};
	
	cout<<"Enter a string: ";
	cin>>text;
	
	
	cout<<"Input string is: "<<text<<endl;
	
	return 0;
}

Output

Enter a string: Hello friends how are you?
Input string is: Hello

Consider the output, input string was "Hello friends how are you? but, only "Hello" stored in variable text. Because cin does not take string after the string, as string found cin terminates reading and assign NULL.

Program to read a string using cin.getline() in C++



#include <iostream>
using namespace std;

int main()
{
	//declaring string (character array)
	char text[100]={0};
	
	cout<<"Enter a string: ";
	cin.getline(text,100);
	
	
	cout<<"Input string is: "<<text<<endl;
	
	return 0;
}

Output

Enter a string: Hello friends how are you?
Input string is: Hello friends how are you?

Here, complete string stored in text, cin.getline() allows to get spaces also. I would recommend to read this tutorial How to read a string with spaces in C++?






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.