Home

Awesome

correct_cpp_int_to_word

BranchTravis CICodecov
masterBuild Statuscodecov.io

Correct C++ chapter 'Hello CLI'.

Goal

Prerequisites

Exercise

Write a command-line interface (CLI) program that convert the number 1 to (and including 6) to their words, followed by a newline.

Fail if the user supplies no, two or more arguments

Call to hello_cliOutputExit status
./int_to_wordAny1
./int_to_word 1one (with newline)0
./int_to_word 2two (with newline)0
./int_to_word 3three (with newline)0
./int_to_word 4four (with newline)0
./int_to_word 5five (with newline)0
./int_to_word 6six (with newline)0
./int_to_word nonsenseAny1
./int_to_word 1 2Any1

This is the code you start with:

#include <iostream>
#include <string>
#include <vector>

int main(int argc, char* argv[]) 
{
  if (argc != 2)
  {
    return 1;
  }
  try
  {
    const int i{std::stoi(argv[1])};
    switch (i)
    {
      case 1: std::cout << "one\n"; break;
      case 2: std::cout << "two\n"; break;
      case 3: std::cout << "three\n"; break;
      case 4: std::cout << "four\n"; break;
      case 5: std::cout << "five\n"; break;
      case 6: std::cout << "six\n"; break;
      default: throw std::invalid_argument("i must be in range [1, 6]");
    }
  }
  catch (const std::exception&)
  {
    return 1;
  }
}

External links