Monday 23 February 2015

How to read an entire line from input in C++

Welcome to Logically Proven blog.
This post demonstrates how to read an entire line from input in C++.

 The following example can read only a single word. The white-space terminates the input.

#include<iostream>
#include<string>
using namespace std;

int main()
{
 cout << "Please enter:\n";

 string s;
 cin>>s;
 
 cout << "You entered " << s << '\n';
}

/*Output: Please enter:
This program takes only a single word
You entered This
*/

Note that there is no explicit memory management and no fixed-size buffer that you could possible to overflow.

The following program reads an entire line.

#include<iostream>
#include<string>
using namespace std;

int main()
{
 cout << "Please enter:\n";

 string s;
 getline(cin,s);
 
 cout << "You entered " << s << '\n';
}

/* output: Please enter:
This program reads an entire line.
You entered This program reads an entire line.
*/

Please write your comments if you find anything is incorrect or do you want to share more information about the topic discussed above.

Logically Proven
Learn, Teach, Share

Karthik Byggari

Author & Editor

Computer Science graduate, Techie, Founder of logicallyproven, Love to Share and Read About pprogramming related things.

0 comments:

Post a Comment

 
biz.