Q:

C++ program to read a string

0

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().

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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?

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Most popular and Searched C++ solved programs with Explanation and Output

Similar questions


need a help?


find thousands of online teachers now
C++ program to display name and age... >>
<< C++ program to add two integer numbers using class...