From feb35903983e729c23460d028f04ddecb6f0713d Mon Sep 17 00:00:00 2001 From: Isabell Pflug Date: Tue, 25 Apr 2023 18:51:56 +0200 Subject: [PATCH] :construction: began working on 2.1 --- assignments/02/02_1.cpp | 66 +++++++++++++++++++++++++++++++++++ assignments/02/CMakeLists.txt | 5 +++ 2 files changed, 71 insertions(+) create mode 100644 assignments/02/02_1.cpp create mode 100644 assignments/02/CMakeLists.txt diff --git a/assignments/02/02_1.cpp b/assignments/02/02_1.cpp new file mode 100644 index 0000000..09bebd3 --- /dev/null +++ b/assignments/02/02_1.cpp @@ -0,0 +1,66 @@ +#include +#include +#include + +int check_number(char* number, int* checked_number) { + std::size_t pos; + *checked_number = std::stoi(number, &pos); + return 0; +} + +int guess(int to_guess) { + std::cout << "Take a guess!" << std::endl; + char* guess; + std::cin >> guess; + int guess_number; + int check = check_number(guess, &guess_number); + if (check < 0) + return check; + if (!guess_number == to_guess) { + if (guess_number < to_guess) + std::cout << "Your number is too small."; + else + std::cout << "Your number is too big."; + return 0; + } + return 1; +} + +int play(int max) { + srand(time(NULL)); + int random_number = rand() % (max + 1); + int win = 0; + int tries = 0; + while (win == 0) { + tries++; + win = guess(random_number); + } + if (win < 0) + return win; + return tries; +} + +int main(int argc, char *argv[]) { + int max = 10; + if (argc > 1) { + int check = check_number(argv[1], &max); + if (check < 0) + return check; + } else + std::cout << "Using default max of 10" << std::endl; + + std::cout << "Do you want to play? (y/n)" << std::endl; + char* answer; + std::cin >> answer; + if (answer[0] == 'y') { + int check = play(max); + if (check < 0) { + std::cout << "Something went wrong. :/" << std::endl; + return check; + } else + std::cout << "Win after " << check << " tries." << std::endl; + } + else + std::cout << "Good night." << std::endl; + return 0; +} diff --git a/assignments/02/CMakeLists.txt b/assignments/02/CMakeLists.txt new file mode 100644 index 0000000..7ccac2a --- /dev/null +++ b/assignments/02/CMakeLists.txt @@ -0,0 +1,5 @@ +cmake_minimum_required(VERSION 3.11.4) +project (01) + +add_executable(02_1 02_1.cpp) +#add_executable(01_2 01_2.cpp)