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().
#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?
Program to read a string using cin in C++
Output
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++
Output
need an explanation for this answer? contact us directly to get an explanation for this answer