Nesting int main() inside int main() - c++

I am trying to make the simplest of all games, but with a loop function.
I'm given the error "a function-definition is not allowed here before '{', as well as a whole list of [Error] expected '}' at end of input.
Am I not allowed to nest int main() within another? Is that my issue at all? How do I accomplish this code without the nesting?
My knowledge and experience extend no more than a few chapters in two books.
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
char again = 'y';
while (again == 'y')
int main()
{
srand(static_cast<unsigned int>(time (0)));
int secret = rand() % 100 +1;
int tries = 0;
int guess;
cout << "\tGuess the random number\n\n";
do
{
cout << "Enter a guess: ";
cin >> guess;
++ tries;
if (guess > secret)
{
cout << "Too High!\n\n:";
}
else if (guess < secret)
{
cout << "Too Low!\n\n";
}
else
{
cout << "\nThat's It! You go it in " << tries << " guesses!\n";
}
} while (guess != secret);
}
cout << "\n\tWould you like to play again? (y/n): ";
char again;
cin >> again;
}

Your issue is nesting a main function inside of the existing main function. (This is not allowed.) In general, (With the exception of some stuff you can do with structs/lambdas which approximate that kind of functionality) you shouldn't nest functions inside of each-other. If you merely remove the function declaration, then your code should work fine:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
char again = 'y';
while (again == 'y')
{
srand(static_cast<unsigned int>(time (0)));
int secret = rand() % 100 +1;
int tries = 0;
int guess;
cout << "\tGuess the random number\n\n";
do
{
cout << "Enter a guess: ";
cin >> guess;
++ tries;
if (guess > secret)
{
cout << "Too High!\n\n:";
}
else if (guess < secret)
{
cout << "Too Low!\n\n";
}
else
{
cout << "\nThat's It! You go it in " << tries << " guesses!\n";
}
} while (guess != secret);
cout << "\n\tWould you like to play again? (y/n): ";
cin >> again;
}
}

As far as I know, you cannot nest int main() inside of int main() for a number of reasons. In general, you can't define one function inside of another (defining "locally"). However, even if you can, your desire to do so should be a massive red flag that your design is off.
NOTE: As Nathan Oliver pointed out in the comments, you can forward-declare a function "locally" (within another function), but the actual implementation must be outside. Even doing this, you should usually second-guess your design at this point.
You need to be asking yourself what you're trying to do.
Are you wanting to group code together under a function to call repeatedly? Then create a separate function (with a different name) outside of main().
Are you wanting to repeat code? If so, you need a loop or a recursive function structure.
Are you wanting to split up some behavior into several functions, but hide all but one function involved? If so, look into classes (not necessarily objects - you can also have static classes.)
Those are just three of many possibilities, and deciding exactly what you want to do and how you want to do it is your responsibility alone to decide, as a programmer.
Brief recap: as far as C++ (and C) are concerned, if you're trying to declare any function inside any other function, you are doing something seriously wrong in design.
On a more technical note, you should also understand precisely what int main() is. It is a special function that is the entry point for your program. No C or C++ program can run without an int main().
You have to have a single instance of this function in main.cpp in order for your program to work. If you have more than one int main(), the computer cannot likely will not be able to find the entry point.
Besides that, having more than one function called main() anywhere in your code is a great way to confuse yourself and others.
In short, you should only have one int main() per program, no exceptions.

Related

Why is my variable not declared in the scope?

I'm working on an assignment right now and when run my code returns this error:
main.cpp:60:20: error: ‘dataArr’ was not declared in this scope
if(tolower(dataArr[i].last) == tolower(lastName))
I'm not quite sure what I'm missing here. If I could at least get it to run I'd appreciate it. Thanks.
I thought arrays were declared globally so i thought it wouldn't be an issue in my functions
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct Database
{
string first;
string last;
string ID;
string phoneNum;
};
void lastSearch(string);
void idSearch(string);
int main()
{
Database dataArr[100];
ifstream myFile("library_database.txt");
int count = 0;
while(!myFile.eof() && count < 100)
{
myFile >> dataArr[count].first >> dataArr[count].last >> dataArr[count].ID >> dataArr[count].phoneNum;
cout << dataArr[count].first << " " << dataArr[count].last << " " << dataArr[count].ID << " " << dataArr[count].phoneNum << endl;
count++;
}
int input;
string search;
cout << "Would you like to search by last name or member ID?\n1. Last Name\n2. ID\n> ";
cin >> input;
while(input != 1 || input != 2)
{
cout << "Enter a valid answer.\n> ";
cin >> input;
}
if(input == 1)
{
cout << "Enter last name: ";
cin >> search;
lastSearch(search);
}
if(input == 2)
{
cout << "Enter ID: ";
cin >> search;
idSearch(search);
}
return 0;
}
void lastSearch(string lastName)
{
int num = 0;
for(int i = 0; i < 100; i++)
{
if(tolower(dataArr[i].last) == tolower(lastName))
{
cout << dataArr[i].first << " " << dataArr[i].last << " " << dataArr[i].ID << " " << dataArr[i].phoneNum << endl
num++;
}
}
if(num == 0)
{
cout << "No match was found in the file.";
}
}
voidSearch was removed to allow this to be posted
To answer the title of your post: because it isn't.
You declare dataArr in main, but you are trying to use it in lastSearch, so lastSearch can't see it. But you can pass it in as a parameter, that's probably the easiest fix:
void lastSearch(const string lastName, const Database *dataArr) { ... }
and call it like this:
lastSearch (search, dataArr);
Note the use of const (get into the habit of doing that whenever you can) and that your array 'decays' to a pointer when you pass it as a parameter like this, so don't be tempted to use sizeof in lastSearch. If you need to know the number of elements in the array, pass that as a parameter too.
Or, better, use std::array instead of a C-style array and then the size of the array is available in lastSearch without the need to pass it in separately. If you do that, you probably want to pass it by const reference to avoid copying it every time you call the function.
Finally, it might be time to learn about std::vector. At the expense of a little more complexity (but not much), this would avoid the need to allocate a fixed size array. Again, for the same reason, pass it around by reference.
Some bedtime reading: The Definitive C++ Book Guide and List
Arrays are not declared globally, they are declared where you declare them :-)
In your case, you declare it at the top of main() so that is its scope, from point of declaration to end of main(). Trying to use it in lastSearch() is therefore invalid.
The easiest fix is probably just to move the declaration immediately before main() so that it is global. But the easiest things is often not the right thing.
You would be better off embracing C++ fully(1) and using something like std::vector, whose size isn't arbitrarily limited to 100 (for example) and which you could pass around quite easily, something like:
#include <iostream>
#include <vector>
void function(const std::vector<int> &vec) {
std::cout << vec.size() << ' ' << vec[0] << '\n'; // Output: 2 42
}
int main() {
std::vector<int> x;
x.push_back(42);
x.push_back(99);
function(x);
}
The main advantages with vectors are that:
you're not limited to a maximum of 100 items;
you don't have to pass around the actual count of items read separately as with a raw array or even a std::array (you don't do that in your code but I assure you, that's a problem).
the size of the vector is an integral property of the vector, available anywhere the vector is in scope.
(1) There's a variety of developers I like to call C+ developers. These are the people that, though they claim to be C++ developers, have never really embraced the C++ way of doing things, sticking to C style programming practices like non-smart pointers or normal arrays :-)
Some of those things may still have a place in modern C++ code but you should be circumspect in their use.

My homework assignment requires me to use booleans in functions. Do I need to pass them to the functions?

For my homework assignment I'm supposed to make a create-your-own-adventure story. There are certain words in the text that are in all caps to represent boolean values that I need to display at the end if the player got them, like a status effect or something. I'm having trouble figuring out how to pass the booleans to the functions so that it makes it to the end of the program where I can display it. My program has functions within functions.
I've tried making the function that sets the boolean to true a boolean itself, then returning the boolean but that just ends the program it seems. I've also tried passing it through the first function call to see if it reaches the second but it doesn't seem like it wants to.
void A1();
bool A100(bool INTIM);
void A167();
void A232();
void A290();
void A13();
void A212();
void A173();
void A159();
void A161();
int main() {
bool INTIM;
A1();
cout << INTIM << endl;
return 0;
}
void A1()
{
int choice;
cout << "Well, Mr Artanon, ...\n 1. ’It’s you who’ll get a rare cut
across that corpulent neck of yours if you don’t speed things along, you
feckless blob of festering lard.’\n 2. ’Surely in such an industrious
kitchen, there must be a starter or two ready to send along and sate His
Abhorentness’s appetite?’\n (enter a menu option): ";
cin >> choice;
while (choice != 1 && choice != 2)
{
cout << "Enter in a valid choice (1 or 2)";
cin >> choice;
}
if (choice == 1)
{
A100();
}
if (choice == 2)
{
A167();
}
}
bool A100(bool INTIM)
{
int choice;
INTIM = true;
cout << " Repugnis turns a paler...\n 1. Onwards, Mr Artanon.\n (enter
in a menu option): ";
cin >> choice;
while (choice != 1)
{
cout << "Enter in a valid option (1)";
}
return INTIM;
A232();
}
What I'm wanting to happen is, the bool INTIM to be passed along so i can display it back in main with the cout statement. I know it will just be a 1 or 0 at the end but I'm just trying to get it to show up at least in the end when I display it. Again there are functions within functions in this program and that might be my problem but I wouldn't think so. There is also functions that come after this, this is not the end of the program and if I need to post the whole thing I will
Calling A100 as written, you need to pass in INTIM and accept the return value
INTIM = A100(INTIM);
But... The initiqal state of INTIM is never used, so you could
INTIM = A100();
and change A100 to look more like
bool A100()
{
int choice;
cout << " Repugnis turns a paler...\n 1. Onwards, Mr Artanon.\n (enter in a menu option): ";
cin >> choice;
while (choice != 1)
{
cout << "Enter in a valid option (1)";
cin >> choice; // added here because otherwise choice never changes
// and this loop will go on for a long, long time.
}
A232(); // moved ahead of return. Code after a return is not run
return true;
}
But since A232 is called and may set additional flags you cannot return, you have a design flaw: What if A232 also modifies a boolean? You can only return one thing from a function. You could pass A232's boolean in by reference, but what it A232 then calls B484 and it also has a boolean?
You don't want to have to pass around every possible boolean, that would be a confusing mess, so consider making a data structure that stores all of your booleans to pass around.
And that leads to an even better idea: encapsulating the booleans and the functions in the same data structure so that you don't have to pass anything around; it's all in the same place.
Do I need to pass them [the boolean results] to the functions?
Often, but not always, it is my preference to pass them by reference, and yes, it can get to be a big chain thru many functions. sigh.
But your question is "Do you need to pass them ...".
The answer is No.
Because
a) you have tagged this post as C++, and
b) the key feature of C++ is the user-defined-class.
Consider declaring every 'adventurous function' of your story within a class scope.
Each 'adventurous function', as an attribute of the class, is implemented with one 'hidden' parameter, the 'this' pointer to the class instance.
So .. if you place all your 'result' booleans as data attributes of the class, invoking any 'adventurous function' will also 'pass' all the class instance data attributes (all your bools!) as part of the invocation. No data is actually moving, just a pointer, the 'this' pointer.
It might look something like this:
#include <iostream>
using std::cout, std::cerr, std::flush, std::endl;
// using std::cin;
#include <iomanip>
using std::setw, std::setfill;
#include <sstream>
using std::stringstream;
#include <string>
using std::string;
namespace AS // Adventure Story
{
class CreateYourOwnAdventureStory_t
{
private:
// diagnostic purposes
stringstream ssUI;
// command line arguments concatenated into one string
// contents: strings convertable to ints to mimic cin
bool INTIM;
// other results go here
public:
int operator()(int argc, char* argv[]) {return exec(argc, argv);}
private:
int exec(int argc, char* argv[])
{
int retVal = 0;
// capture all command line arguments into a string
for (int i=1; i<argc; ++i)
ssUI << argv[i] << " ";
cout << "\n ssUI: " << ssUI.str() << "\n\n\n";
A1();
cout << "\n INTIM : " << INTIM << endl;
// ?more here?
return retVal;
}
void A1()
{
int choice = 0;
cout << "Well, Mr Artanon, ...\n "
"\n 1. ’It’s you who’ll get a rare cut across that corpulent neck of yours "
"if you don’t speed things along, you feckless blob of festering lard. "
"\n 2. ’Surely in such an industrious kitchen, there must be a starter or two "
"ready to send along and sate His Abhorentness’s appetite?’"
"\n (enter a menu option): ";
ssUI >> choice; // cin >> choice;
if (choice == 1) { A100(); }
if (choice == 2) { A167(); }
}
void A100()
{
int choice = 0;
INTIM = true;
ssUI >> choice; // cin >> choice;
cout << "\n\n A100() choice:" << choice
<< " INTIM: " << INTIM << endl;
}
void A167()
{
int choice = 0;
INTIM = false;
ssUI >> choice; // cin >> choice;
cout << "\n\n A167() choice:" << choice
<< " INTIM: " << INTIM << endl;
}
// other action-functions go here
}; // class CreateYourOwnAdventureStory_t
typedef CreateYourOwnAdventureStory_t CreateYOAS_t;
} // namespace AS
int main(int argc, char* argv[]){return AS::CreateYOAS_t()(argc,argv);}
Notes:
This example grabs the command line parameters and appends them to a string stream. The result is use-able in a fashion much like your cin statements.
Did you notice you (probably) will not need forward declarations for your functions? The compiler has to scan a lot of the class declaration to decide various issues, and thus can figure out that A100 (and A167) are actually with-in the scope of AS::CreateYOAS_t::. The functions can still be moved into a cpp file, so you can still take advantage of separate compilation. (and maybe save some effort compiling smaller files, and only the changed files.)
Did you notice that the functions accessing INTIM simply use the bool, without needing any 'this->' to de-reference?
Main invokes a simple Functor. Nothing else. Main invokes operator(). Simple, minimal. The ctor and dtor are currently default. If you need to use the ctor to initialize results or other intermediate info, I would simply add it near the operator() implementation.
PS: You mentioned using bools to return results. You might as, an alternative, consider using a stringstream ... a single stream with text ... use like a log for capturing the ongoing game, or for a single simple overall report to the user.
Good luck.

Changing variables during if-else if- else statements in C++

As I'm sure the question makes clear, I'm new and learning and I'm sure many will wonder why ask.....cause I get the rest of it, just not this. I am using C++ and am trying to make a self guessing program, that uses an algorithim given to me. I have played with this section of code multiple ways and so far the one thing I have narrowed down, is what its not doing, and I want to both understand why and how to fix it because nothing I have tried is working. The basic version of the code I have been playing with is this:
// test_room.cpp : This file contains the 'main' function. Program execution
//begins and ends there. This is where
//I am going to test some code to understand my mistakes and how to fix
//them.
//
#include "pch.h"
#include <iostream>
#include <cstdlib>
#include<ctime>
using namespace std;
int main()
{
char play = 'y';
while (play == 'y')
{
int bad = 27;
int a = 50;
int b = 1;
int good = ((a - b) / 2);
int s = 0;
cout << "\nBegin?";
cin >> play;
do
{
++s;
if (good > bad)
{
cout <<"\n" <<good;
cout <<"\n" << s;
--a;
}
else if (good < bad)
{
cout << "\n"<<good;
cout <<"\n" << s;
++b;
}
else
{
cout << "good job";
}
} while (s < 50);
}
cout << "\nOK\n";
return 0;
}
What my question is I have tried moving the variables, I have fixed brace issues, I have tried using cin>>good>>a or b(depending on >< ) and so far I can not manipulate variables a or b to get it to try to guess or figure out the number 27, all it does is repeat 24 50 times. What do I need to do to change the values of a and b based on the algorithim?
Good and bad are never changed in the loop, I don't really understand the purpose of you algorithm(it looks like a binary search, but not really), but if you aren't changing any values that the if conditions evaluate in the loop, then none of the other conditions will ever be evaluated.

Returning to main() in c++

I just got into c++ and I'm just experimenting. I want to make a simple program which takes users input and calls one of 2 functions, then the function will print a line and ask the user if they want to go again. The issue is c++, for some reason, does not allow me to call main by simple saying main();
Is there any way to call the main function from another function? I am looking for the simplest solution there is, but I can't find anything :/
Here's the code:
#include <iostream>
#include <string>
using namespace std;
int do_math() {
cout << "Math" << endl;
string user;
cout << "would you like to go again? (y or n): " << endl;
cin >> user;
if (user == "y") {
main();
}
else if (user == "n") {
cout << "Okay, bye!";
exit(0);
}
return 0;
}
int do_eng(){
cout << "Eng";
string user;
cout << "would you like to go again? (y or n): " << endl;
cin >> user;
if (user == "y") {
main();
}
else if (user == "n") {
cout << "Okay, bye!";
exit(0);
}
return 0;
}
int main() {
string user;
cout << "Would you like to do math or end?:";
cin >> user;
if (user == "math") {
do_math();
}
else if (user == "end") {
do_eng();
}
return 0;
}
The issue is c++, for some reason, does not allow me to call main by
simple saying main(); Is there any way to call the main function from
another function? I am looking for the simplest solution there is, but
I can't find anything :/
No, you don't want to call main from any of your code.
Not that you should want to do this ... but the simplest solution is to provide a callable function, and get into it in the simplest way from main.
Perhaps:
int myMain()
{
string user;
cout << "Would you like to do math or end?:";
cin >> user;
if (user == "math") {
do_math();
}
else if (user == "end") {
do_eng();
}
return 0;
}
int main(int, const char**)
{
return myMain();
}
Lesson 1 - try to add another level of indirection (i.e. myMain()) does not have the restrictions of main()
Lesson 2 - learn something about recursion ... it seems you probably want to avoid it, here. (i.e. if you always invoke myMain(), how does your program ever terminate?
Lesson 3 - On my system, if the program terminates, I can up-arrow and launch it trivially. Terminal shells do this stuff for you. Perhaps this would be a better approach ... to always terminate unless the user selects one of the action choices (math, burp, etc.)
Lesson 4 - research other programs and how their user interface works. Find a model you like.
Note - I suppose, for your code to call myMain() again, you will need to 'forward declare' the function.
No, the standard specifically disallows calling main() from program code. What you want is to have a loop in main :
int main()
{
bool bContinue;
do
{
/* do something */
std::cout << "Do you want to go again?";
cin >> bContinue;
} while(bContinue);
}

using cin and cout in textmate

I am usually a Java programmer, and have used textmate for that almost exclusively, but lately I started using C++ with it. but when i use even the most basic programs and incorporate the cin keyword, and run the program, I dont get an oppurtunity to put in anything during runtime and sometimes it inserts random values by itself! for example, if i ran this in textmate:
#include <iostream>
int stonetolb(int);
int main() {
using namespace std;
int stone;
cout << "enter the weight in stone";
cin >> stone;
int pounds = stonetolb(stone);
cout << stone << "stone = ";
cout << pounds <<" pounds.";
return 0;
}
int stonetolb(int sts) {
return 14 * sts;
}
I would come out with the output:
enter the weight in stone32767stone = 458738 pounds.
Why is this happening, and how do I stop it?
Most likely, the input statement cin >> stone is failing, and stone has an undefined value. You need to check for input failure by using if (cin >> stone) { ... } else { // input failure }. As for why such a simple program would exhibit failing behaviour, I don't know- you would have to check the textmate documentation.