Strings

This program asks the user for their name. With cin, it only reads until the first space or a new line. Instead we use the getline function to read the entire line.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//Reading a name
#include <iostream>
#include <string>
using namespace std;
int main(void) {
  string name;
  cout<<"What is your first name:";
  cin>>name; //reads until the first space or newline
  cin.ignore(100,'\n'); //clears the input buffer
  cout<<"Hello "<<name<<endl;
  cout<<"Enter your full name:";
  getline(cin, name); //reads the whole line
  cout<<"Your full name is "<<name<<endl;
  system("pause");
  return 0;
} //main
CODE
Output:
What is your first name:Robin Banks
Hello Robin Banks
Press any key to continue . . .

NEXT: Recursion