C++ Programming/Exercises/Standard IO

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Exercises for beginners : The Standard IO Stream[edit | edit source]

EXERCISE 1[edit | edit source]

The following challenge will help to reinforce what you've learned, and give you a springboard from which to start experimenting:

Write a simple program which, when run, asks the user for their name and age, and then displays this back to them. Sample input/output and possible wording are provided below:

Hello. What is your name?
Hello, <name>. How old are you?
<name> is <age> years old.
Solution #1
#include <iostream>

using namespace std;

int main(int argc, char** argv){

  // Get the name
  string name;

  cout<<"Hello. What is your name? "<<endl;

  // Get the age
  int age;

  cout<<"Hello, "<<name<<". How old are you? "<<endl;

  // Show the name and age
  cout<<name<<" is "<<age<<" years old."<<endl;

Solution #2
//by blazzer12
// Program which asks the user for their name and age, and then displays back.


using namespace std;

int main()
	string name;
	int age;
	//get name
	cout<<"Hello! What is your name?"<<endl;
	//get age
	cout<<"How old are you, "<<name<<" ?"<<endl;
	//print name and age
	cout<<"So, "<<name<<", you are age is "<<age<<endl;