C++ Programming - Practical 2

Exercise 1

Create new projects and source files in Visual C++ so that you can compile and run each of the following programs from the lectures,

age.cpp

#include <iostream>
using namespace std;

int main()
{
  int age=26;
  cout << "I am " << age << " years old" << endl;
  age++; /* add one */
  cout << "Next year I will be " << age << endl;
  return 0;
}

strings.cpp

#include <string>
#include <iostream>

int main(void)
{
	std::string s1 = "Hello World";
	std::string s2 = "Hello";
	std::string s3 = " World";

	s2 += s3;

	if(s1 == s2)
	{
		std::cout << "LOOK - EASY!!!\n";
		return(0);
	}
	else
	{
		std::cout << "Oops!\n";
		return(1);
	}
}

cout.cpp


#include <string>
#include <iostream>

int main(void)
{
	std::string s1 = "Hello World\n";
	std::cout << s1;
	std::cout << "Hello again" << std::endl;
}

Exercise 2

This exercise is taken from the first chapter of "Essential C++"

  1. Read, copy, compile and execute the following program:
    #include <iostream>
    #include <string>
    using namespace std;
    
    int main()
    {
    	string user_name;
    	cout << "Please enter your first name: ";
    	cin >> user_name;
    	cout << endl
    	     << "Hello, "
    	     << user_name
    	     << "... And goodbye!" << endl;
    	return 0;
    }
      
  2. Comment out the string header file:
    // #include <string>
    Now recompile the program. What happens?
     
  3. Change the name of main() to my_main(). What happens?
     
  4. Try to extend the program
    1. Ask the user to enter both a family and a given name
    2. modify the output to print both names.