Skip to content

Latest commit

 

History

History
148 lines (107 loc) · 3.26 KB

12_exercises.md

File metadata and controls

148 lines (107 loc) · 3.26 KB

< Back

12. Hello World

Exercise 120

Hello std::cout on Compiler Explorer

Compiler Explorer is a website where you can experiment with many different C++ compilers. You can compile short C++ programs, run them and inspect their assembly.

Today, we will use it to compile and run a Hello World program.

  1. Play with Hello World on Compiler Explorer.
  2. You can save the file on Compiler Explorer locally by pressing ctrl+S when you are on the web page
#include <iostream>

int main() {
  std::cout << "Hello World!\n";
}

Exercise 121

Hello {fmt} on Compiler Explorer

"{fmt} is an open-source formatting library providing a fast and safe alternative to C stdio and C++ iostreams." From the {fmt} GitHub page

In C++20 we are getting parts of this functionality in std::format.

In C++23 we might get std::print.

  1. Play with Hello World on Compiler Explorer
  2. You can save the file on Compiler Explorer locally by pressing ctrl+S when you are on the web page
#include <fmt/format.h>

int main () {
    fmt::print("Hello {}", "World");
}

String concatenation

Set the values of the std::string variables hello and world to the appropriate strings to make the test pass.

TEST_CASE("Exercise 122 : String concatenation", "[.][12]") {
  std::string hello = "";
  std::string world = "";
  REQUIRE(hello + world == "Hello World");
}
Solution
TEST_CASE("Exercise 122 : String concatenation", "[12]") {
  std::string hello = "Hello ";
  std::string world = "World";
  REQUIRE(hello + world == "Hello World");
}

std::string append

Use std::string::append to append the string "World" to hello_world.

TEST_CASE("Exercise 123 : std::string append", "[.][12]") {
  std::string hello_world = "Hello ";
  // append "World"
  REQUIRE(hello_world == "Hello World");
}
Solution
TEST_CASE("Exercise 123 : std::string append", "[12]") {
  std::string hello_world = "Hello ";
  hello_world.append("World");
  REQUIRE(hello_world == "Hello World");
}

Function call

Make a function above the test that returns the string "Hello World"

TEST_CASE("Exercise 124 : Function call", "[.][12]") {
  std::string hello_world = "CALL A FUNCTION";
  REQUIRE(hello_world == "Hello World");
}
Solution
std::string hello() { return "Hello World"; }

TEST_CASE("Exercise 124 : Function call", "[12]") {
  std::string hello_world = hello();
  REQUIRE(hello_world == "Hello World");
}