Cannot jump to label 'fin', error: from here, and crosses initialization - c++

My biggest problems are all stated above, the inability to jump to label fin (error on line 27), the error: from here (error on lines 12 and 14) and the crosses initialization error (error on line 20) Please help!
#include <iostream>
#include <string>
int main()
{
std::string name;
std::cout << "Please comply. y/n: ";
std::string answer;
std::cin >> answer;
if (answer == "y"){std::cout << "You were spared." << std::endl; goto fin;}
if (answer == "Miche"){std::cout << "The killers understood that you understood the prophecy, so they took you to their master" << std::endl; goto secret;}
if (answer == "n"){std::cout << "You were brutally killed." << std::endl; goto fin;}
else {std::cout << "You randomly babled " << answer << ", getting yourself killed."; goto fin;}
secret:
std::cout << "In order to fully find out if you are the legendary Miche, they took you to their leader."
<< " The master looked you over, and asked you one final question. The master asks you, fish?" << std::endl;
std::string fish; fish = "none";
std::cin >> fish;
if (fish == "fish."){std::cout << "You were put in the throne of the king, where you ruled your near killers and their species for eternity."
<< std::endl; goto fin;}
else {std::cout << "You failed and were immediately killed." << std::endl; goto fin;}
goto fin;
fin:
return 0;
}

The problem is, essentially this:
int main() {
if (whatever)
goto fin;
std::string fish;
fin:
return 0;
}
If whatever is true, the goto jumps past the construction of fish. That's not allowed, because the compiler can't generate sensible code to destroy fish or not, depending on whether the goto was executed.
Solution: don't use goto.
Possibilities:
int main() {
if (whatever)
goto fin;
{
std::string fish;
}
fin:
return 0;
Here, fish gets destroyed at the end of the block, so the goto doesn't cause a problem (aside from its inherent unstructured nature).
Better:
int main() {
if (!whatever) {
std::string fish;
}
return 0;
}

You can duplicate the problem using a much simpler function.
void foo()
{
goto fin;
std::string fish = "none";
std::cin >> fish;
fin:
}
Why is that a problem? When the execution jumps to fin:, the code to initialize fish is not executed. Its destructor will be called when the function returns. Since the destructor will be called on an uninitialized object, the program will exhibit undefined behavior.
The simplest fix for your problem is to put almost everything in main in another function, and then use return instead of goto.
void do_stuff()
{
std::string name;
std::cout << "Please comply. y/n: ";
std::string answer;
std::cin >> answer;
if (answer == "y")
{
std::cout << "You were spared." << std::endl;
return;
}
if (answer == "n")
{
std::cout << "You were brutally killed." << std::endl;
return;
}
if (answer == "Miche")
{
std::cout << "The killers understood that you understood the prophecy, so they took you to their master" << std::endl;
}
else
{
std::cout << "You randomly babled " << answer << ", getting yourself killed.";
return;
}
std::cout << "In order to fully find out if you are the legendary Miche, they took you to their leader."
<< " The master looked you over, and asked you one final question. The master asks you, fish?" << std::endl;
std::string fish = "none";
std::cin >> fish;
if (fish == "fish")
{
std::cout << "You were put in the throne of the king, where you ruled your near killers and their species for eternity." << std::endl;
}
else
{
std::cout << "You failed and were immediately killed." << std::endl;
}
}
int main()
{
do_stuff();
}

Related

Calling a function multiple times but it prints only once

I'm running the following code:
#include <iostream>
using namespace std;
string response(bool isMale, bool isTall)
{
if (isMale && isTall) {
cout << "MALE AND TALL" << endl;
}
else if (isMale || isTall) {
cout << "MALE OR NOT TALL" << endl;
}
else {
cout << "ELSE" << endl;
}
}
int main()
{
response(true, true);
response(false, true);
response(false, false);
return 0;
}
the output is the following:
MALE AND TALL
Process returned -1073740940 (0xC0000374) execution time : 1.460 s
Press any key to continue.
Why isn't the output?:
MALE AND TALL
MALE OR NOT TALL
ELSE
A different forum post hinted at a global value not being reset. I don't really know what to make of that.
I would appreciate any help
void response(bool isMale, bool isTall){
if (isMale && isTall) {
cout << "MALE AND TALL" << endl;
}
else if (isMale || isTall ){
cout << "MALE OR NOT TALL" << endl;
}
else {
cout << "ELSE" << endl;
}
}
You need to change function return type "string" to "void".

C++ Console Application, Outputting Incorrect Data

I've been working on a simple console application and was stopped when, upon compiling my latest code, it began outputting strings of text and integers which did not match what I have entered.
The purpose of the program thus far is simple: to input a string of data and for it to output correctly multiple times in the console application. Below I have linked the pseudocode.
Thanks in advance.
#include <iostream>
#include <string>
void printIntro();
void RunApp();
bool RequestRestart();
std::string GetAttempt();
int main() // entry point of the application
{
printIntro();
RunApp();
RequestRestart();
return 0;
}
void printIntro() {
// introduce the program
constexpr int WORD_LENGTH = 8; // constant expression
std::cout << "Welcome to the Bull and Cow guessing game\n";
std::cout << "Can you guess the " << WORD_LENGTH;
std::cout << " letter isogram I am thinking of?\n\n";
return;
}
void RunApp()
{
// loop for number of attempts
constexpr int ATTEMPTS = 5;
for (int count = 1; count <= ATTEMPTS; count++)
{
std::string Attempt = GetAttempt();
std::cout << "You have entered " << GetAttempt << "\n";
std::cout << std::endl;
}
}
std::string GetAttempt()
{
// receive input by player
std::cout << "Enter your guess: \n";
std::string InputAttempt = "";
std::getline(std::cin, InputAttempt);
return InputAttempt;
}
bool RequestRestart()
{
std::cout << "Would you like to play again?\n";
std::string Response = "";
std::getline(std::cin, Response);
std::cout << "Is it y?: \n" << (Response[0] == 'y'); //response must be in brackets
return false;
}
You have to change this line
std::cout << "You have entered " << GetAttempt << "\n";
instd::cout << "You have entered " << Attempt << "\n";
In this way you do not print the address of the function, just like you did before, but the variable in which you stored the return value of the GetAttempt function.
You are printing a pointer to GetAttempt. Instead print Attempt:-
std::cout << "You have entered " << Attempt << "\n";

Static vector as a class objects container

I've seen many questions and answers about this issue but still I can't solve my problem. How should I initialize a static vector? I'm also asking you for checking I use a default construct properly. I don't mean checking if it's working because I know that it does. I just wonder if it is an elegant implementation?
class Employee
{
private:
static std::vector<Employee> employee;
std::string name;
int age;
Employee::Employee()
{
std::string localName;
int localAge;
std::cout << "So... do you want to hire a new employee? Let's look at CVs " << std::endl;
localName = "Marek"; //GenerateName();
localAge = 21; //these function is not ready yet. it'd be just a rand()
std::cout << "I've got one. What do u think about " << localName << " age " << localAge << "?" << std::endl;
int decision;
do
{
std::cout << "Do you want hire him [1] or not [2] ? " << std::endl;
std::cin >> decision;
switch (decision)
{
case 1:
name = localName;
age = localAge;
decision = 0;
break;
case 2:
employees.erase(employees.end());
decision = 0;
break;
default:
std::cout << "Incorrect option. Try again" << std::endl;
}
} while (decision != 0);
}
public:
static void Employ()
{
employees.push_back(Employee::Employee());
}
};
int main()
{
Employee::Employ();
system("pause");
}
Your code didn't work when I ran it. In addition to adding includes and fixing some typos, I had to add this line:
std::vector<Employee> Employee::employee;
However, I don't think this is the best solution. For sweet clarity's sake, an Employee shouldn't contain a vector of Employees, but should be, well, an employee. If you want a vector of employees, you can declare one in main (or elsewhere). If you want your vector of employees to have some added features like the interactive employee-adding function you wrote, you can do it like this:
class EmployeeForce: public std::vector<Employee>
{
void interactivelyAddEmployee ();
...
};
...
EmployeeForce myStaff;
I've changed entire the concept. The problem was that I unnecessary wanted to put inside the class the container of objects (in this case: std::vector). I know now that class should only contain informations about the single object; it shouldn't know about anything about others one.
class Employee
{
public:
std::string name;
int age;
};
std::ostream& operator<<(std::ostream& out, const std::vector<Employee>& v)
{
out << "[";
for (size_t i = 0; i < v.size(); ++i)
{
out << "Name: " << v[i].name << " age: " << v[i].age;
if (i != v.size() - 1)
out << ", ";
}
out << "]";
return out;
}
Employee generate_random_employee(Employee obj)
{
obj.name = "Marek"; //GenerateName();
obj.age = 21; //these function is not ready yet. it'd be just a rand()
return obj;
}
int main()
{
int decision;
std::string name;
std::vector<Employee> employees;
Employee some_new_employee;
std::cout << "Welcome mrs. manager. What do you want to do today, sir?" << std::endl << std::endl;
do
{
std::cout << "Hire sombody [1], Fire somebody [2], Exit [0] " << std::endl;
std::cin >> decision;
switch (decision)
{
case 1:
some_new_employee = generate_random_employee(some_new_employee);
if (should_i_employ(some_new_employee))
{
employees.push_back(some_new_employee);
}
break;
case 2:
std::cout << "Who do you want to fire?" << std::endl;
std::cin >> name;
if (is_the_employee_exist(employees, name))
{
if (are_u_sure())
{
}
}
else
std::cout << "" << std::endl;
break;
case 3:
std::cout << employees << std::endl;
break;
case 0:
std::cout << "Good bye, sir" << std::endl;
break;
default:
std::cout << "There is not these option. Try again " << std::endl;
}
} while (decision != 0);
system("pause");
}

How to use cin inside a function?

I am new to c++ and am trying to make a simple text based game. The code below is supposed
to welcome the user to the game and ask whether or not the user wants to start the game. I don't get any build errors, but when I run it all it shows is a blank screen. What exactly am I doing wrong?
Code below:
string D1(string Original)
{
cin >> Original;
return Original;
}
int main ()
{
string Decision1;
cout << "Welcome to [game name]" << endl;
cout << "Would you like to start the game?" << endl;
cout << "Yes/No" << endl;
string D1(Decision1);
system("cls");
if (Decision1 == "Yes")
{
cout << "this happens" << endl;
}
else if (Decision1 == "No")
{
cout << "that happens" << endl;
}
}
You have to call D1, not create a new variable named D1:
std::string D1()
{
std::string Original;
std::cin >> Original;
return Original;
}
int main ()
{
std::cout << "Welcome to [game name]" << std::endl;
std::cout << "Would you like to start the game?" << std::endl;
std::cout << "Yes/No" << std::endl;
auto Decision1 = D1();
system("cls");
if (Decision1 == "Yes")
{
std::cout << "this happens" << std::endl;
}
else if (Decision1 == "No")
{
std::cout << "that happens" << std::endl;
}
}
string D1(string Original) should be string D1(string& Original) (ie: passing with reference)
and
string D1(Decision1); in main should be
D1(Decision1); because
string D1(Decision1); actually declares a new string variable, called D1 (same name as the function) and initializes it with the value of Decision1
This statement
string D1(Decision1);
is a definitiom of an object of type std::string with name D1 that initialized by object Decision1. As the object Decision1 is empty then and object D1 is empty.
What you meant is the following
void D1( string &Original )
{
cin >> Original;
}
//...
D1( Decision1 );
or the following
string D1()
{
string Original;
cin >> Original;
return Original;
}
//...
Decision1 = D1();
Take into account that if you use two if statements
if (Decision1 == "Yes")
{
cout << "this happens" << endl;
}
else if (Decision1 == "No")
{
cout << "that happens" << endl;
}
then you have to add a third statement with else because the user can enter neither "Yes" nor "No". Also you should compare strings independently of their case (upper case or lower case). So you have to convert strings to some common case.
For example
#include <cctype>
//...
for ( char &c : Decision1 ) c = std::toupper( c );
if ( Decision1 == "YES" )
{
cout << "this happens" << endl;
}
else if ( Decision1 == "NO" )
{
cout << "that happens" << endl;
}
else
{
//...
}
P.S. And here in comments there was suggested book "Programming -- Principles and Practice Using C++. " I do not advice this book for beginners. In fact it is a bad book for beginners. You will spend much time reading the book but your knowledge of C++ will be close to zero.
string D1(string Original)
Right now, the program will make a copy of the string you pass and place it into Original, so when you come out of the function, nothing will have happened to Decision1.
What you want it to do is pass the variable by reference.
Passing a variable by reference means the function isn't receiving a copy of what was passed, but the actual variable you passed (imagine a voodoo doll). Anything you do to the variable in the function will take effect on the variable passed.
Change the function header to:
string D1(string &Original)

String Game, creating a specific Loop? c++

Im new to programming and C++ and I started making a little string type game for fun, which gives the user two options through out the program, but in the final part of the program i cant get it to output a unique option for the final input(makeCure) - which i only want to output at the end not through out the program. Hope Im making sense :/ .Iv tried and tried and tried and the more i try the more probloms I create. Iv shown below in my code where Im sure the problom lies. Any advice would much appreciated.
#include<iostream>
#include<string>
using std::string;
bool intro(void);
void room(bool enemy, bool data, bool cure, string description);
//player stats
string Name = "";
//enemy states
string enemyName = "";
//data stats
string dataName = "";
//Cure - Option in room7 only
string makeCure = "";
//room descriptions(string constructs)
const string room1 = "You enter the first town of infected Zombies.";
const string room2 = "You are overwelmed by Zombies, and plunder into the sewers to escape.";
const string room3 = "You make your way to safety and find yourself in the Central Town Hall.";
const string room4 = "You decide to venture into the local forest to find the finalingrediants";
const string room5 = "You venture further for the final ingrediant, into a nearby Cave.";
const string room6 = "Its time for you to face the Zombie General!!!";
const string room7 = "You work day and Night in the Labs to make the Cure.";
int main(void)
{
if(intro())
return 0;
dataName = "First Ingrediant- Zombie Rags with infected DNA";
enemyName = "Zombie Soldior";
room(true, true, false, room1);
enemyName = "Massive Zombie Rat";
room(true, false, false, room2);
dataName = "Seconed Ingrediant- StemCells";
enemyName = "Mutated Scientists";
room(true, true, false, room3);
dataName = "Third Magic-Mushrooms";
room(false, true, false, room4);
dataName = "Fourth Final Ingrediant - Coffee Beans";
enemyName = "Commander Zombie";
room(true, true, false, room5);
enemyName = "Zombie General";
room(false, true, false, room6);
return 0;
makeCure = "Elixier to Save the World";
room(false, false, true, room7);
return 0;
}
bool intro(void)
{
using std::cout;
using std::cin;
cout << "Brave Soul!!! What is your name?\n";
cin >> Name;
cout << "Ahh... " << Name << " You say.." << "How about Zombie Slayer?.. Good, glad we agree!\n";
cout << "Humanity is in need of your Help, "
<< "The world is being infected by the\n"
<< "ZD1678 ZOMBIE VIRUS \n"
<< "And we need to send you to Cape Town to stop the central spread.\n"
<< "Your task will be tough, but we know you can do it \n"
<< "Will you accept the challenge?\n\n";
cout << "1)Yes. \n"
<< "2)No. \n\n";
int response;
cin >> response;
return !(response ==1);
}
void room(bool enemy, bool data, bool cure, string description)
{
using std::cout;
using std:: cin;
while(true)
{
cout << description.c_str() << "\n\n";
int response = 0;
do
{
cout << "Shall Our Hero continue his Quest?\n";
if(enemy)
cout << "1) Attack the "
<< enemyName.c_str() << "\n";
else if(!enemy)
cout << "1) venture further....";
if(data)
cout << "2)Pick up the "
<< dataName.c_str() << "\n";
cin >> response;
/* Trying to create the last if that only kicks in at room7( string makeCure )
* that displays the option to make the cure
* This is where my Problem is.
* Iv tried anouther if
* and else
* and while and nothing works, its just messes up everything..
* badly
*/
} while(response < 1 || response > 2);
switch(response)
{
case 1:
if(enemy)
{
enemy = !enemy;
cout << "You slay the deadly "
<< enemyName.c_str() << "\n";
}
else if(!enemy)
return;
break;
case 2:
data = !data;
cout << "You pick up the "
<< dataName.c_str() << "\n";
break;
}
}
}
what you probably want to do is dynamically generate a list of possible events each time you write out the list and present it to the user, then you can match the response to the list to get what the user wants to do. like this:
enum EventType
{
ET_Enemy,
ET_Item,
ET_Cure,
ET_Continue,
ET_MAX
};
void room(bool enemy, bool data, bool cure, string description)
{
using std::cout;
using std:: cin;
int currentEventChoices[ET_MAX];
int numEventChoices;
while(true)
{
cout << description.c_str() << "\n\n";
int response = 0;
do
{
numEventChoices = 0;
cout << "Shall Our Hero continue his Quest?\n";
if(enemy)
{
cout << (numEventChoices+1) << ") Attack the "
<< enemyName.c_str() << "\n";
currentEventChoices[numEventChoices] = ET_Enemy;
numEventChoices++;
}
if(data)
{
cout << (numEventChoices+1) << ") Pick up the "
<< dataName.c_str() << "\n";
currentEventChoices[numEventChoices] = ET_Item;
numEventChoices++;
}
if(cure)
{
cout << (numEventChoices+1) << ") cure related string "
<< makeCure.c_str() << "\n";
currentEventChoices[numEventChoices] = ET_Cure;
numEventChoices++;
}
cout << (numEventChoices+1) << ") venture further....\n"; // note if this is only meant to be an option if there is no enemy, put it in an else after the if(enemy)
numEventChoices++;
cin >> response;
} while(response < 1 || response > numEventChoices);
switch(currentEventChoices[response-1])
{
case ET_Enemy:
enemy = !enemy;
cout << "You slay the deadly "
<< enemyName.c_str() << "\n";
break;
case ET_Item:
data = !data;
cout << "You pick up the "
<< dataName.c_str() << "\n";
break;
case ET_Cure:
//do cure stuff
break;
case ET_Continue:
return;
}
}
}
the trouble you are having is that by just using a very static next of if/else statements each time you want to match the option number to the event, it gets very complex and messy, it was fine when there was just the 4 cases of there being an enemy or not, or data or not. but now you are adding another branch with cure, its just got really complex to do it that way.
It's a bit hard to understand what you need, so tell me if it's not what you wanted.
Using braces and indenting consistently can really help with this:
do {
cout << "Shall Our Hero continue his Quest?\n";
if (enemy) {
cout << "1) Attack the " << enemyName << "\n";
} else {
cout << "1) venture further....";
}
if (data) {
cout << "2) Pick up the " << dataName << "\n";
}
if (cure) {
cout << "2) take the " << makeCure << "\n";
}
cin >> response;
} while (response < 1 || response > 2);
and fix "case 2" in the switch part:
case 2:
if (data) {
data = false;
cout << "You pick up the " << dataName << "\n";
} else if (cure) {
// fill in ...
}
break;
Notes:
You can use endl (from std) instead of '\n'. cout << "hello" << endl;
You can pass many of your global variables as arguments, so you won't need them to be global (global is bad, in general).
Much of your game can be be squeeszed into arrays and structs - being "data driven" and "table driven". I don't know if you got there already, but you can try and identify these parts.
if(enemy) ... else if(!enemy) you don't need the !enemy part. it is implied by the else.