Jump to content

C++ Programming/Exercises/Standard IO

From Wikibooks, open books for an open world

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;
  cin>>name;

  // Get the age
  int age;

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

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

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

#include<iostream>

using namespace std;

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