Hi,
I am trying to recreate the UFO project from scratch using my own code built. I am not yet finished the code and halfway through, and not yet put them into several functions. The code is as follows;
#include <iostream>
#include <vector>
int main() {
std::string codeword = "codecademy";
std::string answer = "__________";
char input;
bool guess = false;
for (int i = 0; i < codeword.size(); i++){
std::vector<char> add;
std::cout << "\nInsert your letter: ";
std::cin >> input;
//check if input is present in any letter in the string
for (int l = 0; l < codeword.size(); l++){
if (input == codeword[l]){
guess = true;
break;
}
}
//if guess == true, create vector add
if (guess == true){
for (int j = 0; j < codeword.size();j++){
if (input == codeword[j]){
add.push_back(codeword[j]);
}
else {
add.push_back(answer[j]);
}
}
}
//if input_not_codeword()
else if (guess == false){
std::cout << "\nYou are closer to be abducted. Behold!\n";
}
//print the vector
for (int k = 0; k < add.size();k++){
std::cout << " " << add[k];
}
//convert vector to string and store the string answer as new_ans
std::string new_ans(add.begin(), add.end());
answer = new_ans;
guess = false;
//if answer = codeword, we succeed!
if (answer == codeword){
break;
}
}
if (answer == codeword){
std::cout << "\nYeah, we saved the world!!!!!!!\n";}
else {
std::cout << "\nDoom of the world\n";}
}
The partially completed code supposed to run as follow;
- The computer will prompt to guess word
- if the guess letter is correct, it will be added to the vector. And the vector will be printed
- If the guess letter is wrong, warning will be prompt.
- If the guess word is correct, computer will kind of congrats me.
- After a few attempts with wrong guess, computer will end the program with some another message.
However, when I run the following function, when I insert the right letter, it is successfully be printed. Everything is fine, only after I insert the first letter of the word. After that, if I enter the wrong letter, the vector that contained the first letter of the word get emptied. And only appear after I rewrite the first letter. I could not be sure where is wrong as the first element of the vector kind of getting replaced by something.
You can try yourself. Hope someone can help to explain.
The link to the project is [https://www.codecademy.com/projects/practice/cpp-ufo]