Small Steps VI — Growing into C++
Showing where a name belongs
Show where a name belongs.
What you will learn
A namespace groups names to distinguish them. :: identifies the namespace a name belongs to.
Try it
Example · example2.cpp
#include <iostream>
#include <string>
void small_main()
{
Small::String small_text = "Small namespace";
Small::print(small_text);
std::string standard_text = "Standard namespace";
std::cout << standard_text << "\n";
}
Small::print and std::cout are different tools. The example prints Small namespace and Standard namespace in that order.
A namespace is not an object. Distinguish the dot in window.show() from :: in Small::print.
Exercise
Create std::string name, read a line with std::getline(std::cin, name), and print it back with std::cout.
Exercise starter · exercise2_starter.cpp
#include <iostream>
#include <string>
void small_main()
{
std::string name;
// Ask for a name, read a line, and print it.
}
Hint
Include <iostream> and <string>, print a prompt with cout, then call getline.
show solution
#include <iostream>
#include <string>
void small_main()
{
std::string name;
std::cout << "Name: ";
std::getline(std::cin, name);
std::cout << "Hello, " << name << "\n";
}