Thread: Recalling Functions?

  1. #1
    Registered User
    Join Date
    Feb 2005
    Posts
    18

    Recalling Functions?

    First off, I'd just like to point out that I'm quite new to C++. Anyways, I'm trying to make an inline function return to the main function if a switch case is met. The compiler error is as follows:

    --------------------Configuration: healthfair - Win32 Debug--------------------
    Compiling...
    healthfair.cpp
    C:\CS151\healthfair\healthfair.cpp(66) : error C2065: 'main' : undeclared identifier
    C:\CS151\healthfair\healthfair.cpp(97) : error C2373: 'main' : redefinition; different type modifiers
    Error executing cl.exe.

    healthfair.exe - 2 error(s), 0 warning(s)

    Here is the code (I will bold and enlarge the two error lines for easier reading):

    Code:
    // Health Fair
    // Created by Ty Guenley
    // 02-09-05
    
    #include <iostream.h>
    
    // Required header and namespace for colors
    #include "Console.h"
    namespace con = JadedHoboConsole;
    
    // Body Mass Index Inline Function
    inline void bmi()
    {
        // Required Variables
        char bmireturn;
        int feet, inches, pounds;
        float meters, kilograms, bmi;
    
        // Required stream for colors
        using std::cout;
        using std::endl;
    
        // Clear Screen
        cout << con::clr;
    
        // Body Mass Title and Intro
        cout << con::fg_gray << "-" << con::fg_white << "="
            << con::fg_cyan << "Body Mass Index" << con::fg_white
            << "=" << con::fg_gray << "-";
    
        // Get User's Height and Weight
        cout << con::fg_white << "\n\nEnter your " << con::fg_cyan
            << con::bg_blue << "WEIGHT" << con::fg_white << con::bg_black
            << "in pounds: ";
        cin >> pounds;
        cout << con::fg_white << "\n\nEnter your " << con::fg_cyan
            << con::bg_blue << "HEIGHT" << con::fg_white << con::bg_black
            << "... ";
        cout << "\n\tFeet: ";
        cin >> feet;
        cout << "\tInches: ";
        cin >> inches;
    
        // Make Calculatations
        inches = (feet * 12) + inches;
        meters = inches * (float)0.0254;
        kilograms = pounds / (float)2.2;
        bmi = kilograms / (meters * meters);
    
        // Display Results
        cout << "\nYou are " << con::fg_cyan << meters << "m"
            << con::fg_white << " tall.";
        cout << "\nYour mass is " << con::fg_cyan << kilograms << "kg"
            << con::fg_white << ".";
        cout << "\nYour Body Mass Index is " << con::fg_cyan << bmi
            << con::fg_white << ".";
    
        // Return to main()?
    bmim:
        cout << "\n\nWould you like to return to the main menu? "
            << con::fg_gray << "y/n\n";
        cin >> bmireturn;
        switch (bmireturn)
        {
        case 'y':
         main();
            break;
        case 'n':
            cout << con::fg_white << "\nGood-bye!";
            break;
        default:
            cout << con::clr;
            cout << con::fg_white << "\nPlease choose y/n!";
            goto bmim;
            break;
        }
    }
    
    // Weight Loss Inline Function
    inline void weight()
    {
        // Weight Loss Variables
        int sedentary, calories;
    
        using std::cout;
        using std::endl;
        // Clear Screen
        cout << con::clr;
    
        // Weight Loss Title
        cout << con::fg_gray << "-" << con::fg_white << "="
            << con::fg_cyan << "Weight Loss" << con::fg_white
            << "=" << con::fg_gray << "-\n\n";
    }
    
    void main()
    {
        // Required variables
        int select;
    
        using std::cout;
        using std::endl;
    
        // Main Title and Copyleft
        cout << con::clr;
        cout << con::fg_gray << "-" << con::fg_white << "="
            << con::fg_cyan << "Health Fair 2005" << con::fg_white
            << "=" << con::fg_gray << "-\t(L)2005 Ty Guenley";
    
        // Menu Selection
        cout << con::fg_white << "\n\n\t::" << con::fg_gray
            << "Menu" << con::fg_white << "::";
        cout << con::fg_cyan << "\n\n1. " << con::fg_white << "Body Mass Index";
        cout << con::fg_cyan << "\n2. " << con::fg_white << "Weight Loss";
        cout << "\n\nPlease make a selection: ";
        cin >> select;
    
        // Menu Selection Functions
        switch (select)
        {
        case 1:
            bmi();
            break;
        case 2:
            weight();
            break;
        default:
            cout << con::fg_yellow << con::bg_gray << "/" << con::fg_gray
                << con::bg_yellow << "/" << con::fg_yellow << con::bg_gray
                << "/" << con::fg_white << con::bg_red
                << "Error: Please enter a valid choice!" << con::fg_yellow
                << con::bg_gray << "/" << con::fg_gray << con::bg_yellow
                << "/" << con::fg_yellow << con::bg_gray << "/\n"
                << con::fg_white << con::bg_black;
        }
    }
    is there a better way to do this? or is it even possible to do it period?

    the weight() function is not completed as of yet, but i was going to add the same switch to it as well.

    also, in case it matters, i'm using Visual C++ 6.0

    thanks much!
    Last edited by suzumebachi; 02-14-2005 at 12:12 PM.

  2. #2
    Registered User
    Join Date
    Feb 2005
    Posts
    44
    As far as I know, calling main() is no longer allowed..

    I'm a noob so I can't really help except that I know calling main is a big no-no

  3. #3
    Registered User
    Join Date
    Feb 2005
    Posts
    18
    well, it apparently doesn't matter whether I call it main() or not, I get the same error anyways. :/

    thanks for the reply though.

  4. #4
    Magically delicious LuckY's Avatar
    Join Date
    Oct 2001
    Posts
    856
    1) Don't use goto.

    2) What you're doing is a bad idea even if it was allowed because it is not only recursion, but unnecessary recursion (you could continually go back and forth between the menu and the function).

    3) What you should do is have a menu function that prints the menu and asks where the user wants to go. After the user has made that choice, call the function the user requested and once that function returns you can display the menu again inside a loop.

    e.g.,
    Code:
    void function() {
      // blah
    }
    
    void menu() {
      while (true) {
        char ch;
        // print menu here
        // read input here
        if (ch == '?')
          function();
        else if (ch == 'q')// q for quit
          break;// break out of the loop
      }
    }
    
    int main() {
      menu();
      return 0;
    }

  5. #5
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    #include <iostream.h> ---> #include <iostream>

    You are calling bmi() from main(), so inside bmi() if you want to get back to main, you just use: return.

  6. #6
    Registered User
    Join Date
    Feb 2005
    Posts
    44
    change void main() to int main() and return 0. Many a compiler will complain about this, as will many a poster here

    It looks like that might be why it's complaining -

    -Edit-

    Obviously not, then

    (see 7stud's post)

    But void main is still baaaaad practice

  7. #7
    Registered User
    Join Date
    Feb 2005
    Posts
    18
    When I change <iostream.h> to <iostream>:

    --------------------Configuration: healthfair - Win32 Debug--------------------
    Compiling...
    healthfair.cpp
    c:\cs151\healthfair\healthfair.cpp(35) : error C2065: 'cin' : undeclared identifier
    c:\cs151\healthfair\healthfair.cpp(35) : warning C4552: '>>' : operator has no effect; expected operator with side-effect
    c:\cs151\healthfair\healthfair.cpp(40) : warning C4552: '>>' : operator has no effect; expected operator with side-effect
    c:\cs151\healthfair\healthfair.cpp(42) : warning C4552: '>>' : operator has no effect; expected operator with side-effect
    c:\cs151\healthfair\healthfair.cpp(62) : warning C4552: '>>' : operator has no effect; expected operator with side-effect
    c:\cs151\healthfair\healthfair.cpp(116) : warning C4552: '>>' : operator has no effect; expected operator with side-effect
    Error executing cl.exe.

    healthfair.exe - 1 error(s), 5 warning(s)

    Also: I always thought int main() and return 0; were bad practice?

    Edit: I also tried the menu() thing, but it doesn't work either. I think it's because it's being called before it's being defined. Is there a way to get around this?

    And using return does nothing.
    Last edited by suzumebachi; 02-14-2005 at 01:23 PM.

  8. #8
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    Changing <iostream.h> to <iostream> will bring up the issue of namespaces. For the meantime, until you have a better understanding of what is going on, the easiest solution is to put a using namespace std; declaration after all your headers, i.e.:

    Code:
    #include <iostream>
    using namespace std;
    Quote Originally Posted by suzumebachi
    Also: I always thought int main() and return 0; were bad practice?
    Just the opposite in fact.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  9. #9
    Registered User VirtualAce's Avatar
    Join Date
    Aug 2001
    Posts
    9,607
    You cannot call main() from within a C++ program. You can still do this in C although I have no idea why you would want to.

  10. #10
    Registered User
    Join Date
    Feb 2005
    Posts
    18
    wait, i discovered what was causing return not to work. i removed the break after the call to bmi() in main(). but now it's going straight to weight().

    working on it...

  11. #11
    Registered User
    Join Date
    Feb 2005
    Posts
    18
    I think if and else if is going to work better than switch in the menu because after the function returns, it's moving straight to the next case for some reason.

    Edit: Tried that, and it doesn't work either. Argh!

    I'm going to try the loop idea next. :/

    Edit 2: Before even trying I can see that the loop isn't going to work with the switch for the same reason it won't work without a loop. Gonna try the loop with if and if else.

    Edit 3: Working so far so good, except it won't call the weight() function now.
    Last edited by suzumebachi; 02-14-2005 at 02:00 PM.

  12. #12
    Anti-Poster
    Join Date
    Feb 2002
    Posts
    1,401
    The loop idea is the best idea. This is just a different way doing what Lucky suggested:
    Code:
    void function1()
    {
      // blah
    }
    
    void function2()
    {
      // blah
    }
    
    int main()
    {
       char ch = 0;
       while ((ch != 'q') && (ch != 'Q'))
       {
          // print menu here
          // read input here
          switch(ch)
          {
             case 'a':
                function1();
                break;
             case 'b':
                function2();
                break;
             //and so on
          }
       }
       return 0;
    }
    Quote Originally Posted by suzumebachi
    Edit: I also tried the menu() thing, but it doesn't work either. I think it's because it's being called before it's being defined. Is there a way to get around this?
    Yes, declare the function first. You can do it this way:
    Code:
    void function1();
    void function2();
    
    int main()
    {
       char ch = 0;
       while ((ch != 'q') && (ch != 'Q'))
       {
          // print menu here
          // read input here
          switch(ch)
          {
             case 'a':
                function1();
                break;
             case 'b':
                function2();
                break;
             //and so on
          }
       }
       return 0;
    }
    
    void function1()
    {
      // blah
    }
    
    void function2()
    {
      // blah
    }
    If I did your homework for you, then you might pass your class without learning how to write a program like this. Then you might graduate and get your degree without learning how to write a program like this. You might become a professional programmer without knowing how to write a program like this. Someday you might work on a project with me without knowing how to write a program like this. Then I would have to do you serious bodily harm. - Jack Klein

  13. #13
    Registered User
    Join Date
    Feb 2005
    Posts
    18
    ok i think it actually is calling the weight() function, it's just clearing so fast i can't see it (it never pauses for input or anything, so it flashes for a millisecond and returns to the menu).

    thanks a bunch for the help guys.

    also: am I going overkill on the comments?

    edit: how do I make it pause for the user to press return or space or something after the error message? The error message is also flashing too fast for the user to read. I tried cin.get() but it's not visibly doing anything.
    Last edited by suzumebachi; 02-14-2005 at 02:09 PM.

  14. #14
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    Anytime you have:
    cin >> someVariable;
    It leaves a newline in the input stream, so to flush it use something like:
    cin.ignore(80,'\n');

    Or you could put it after you output the error message, whichever you prefer:
    Code:
    cin.ignore(80,'\n');
    cin.get();

  15. #15
    Registered User
    Join Date
    Feb 2005
    Posts
    18
    ok, it's working now. the code's still kinda messy though.

    here's what I have now:

    Code:
    // Health Fair
    // Created by Ty Guenley
    // 02-09-05
    
    #include <iostream.h>
    
    // Required header and namespace for colors
    #include "Console.h"
    namespace con = JadedHoboConsole;
    
    
    // Defining Necessary Variables
    int pounds, feet, inches, activity, calories, wselect;
    float meters, kilograms;
    char bmireturn, wreturn; 
    
    // Body Mass Index Inline Function
    inline void bmi()
    {
        // Defining Body Mass Index Variable
        float bmi;
    
        // Streams required for colors
        using std::cout;
        using std::endl;
        // Clear Screen
        cout << con::clr;
    
        // Body Mass Title and Intro
        cout << con::fg_gray << "-" << con::fg_white << "="    << con::fg_cyan << "Body Mass Index"
            << con::fg_white << "=" << con::fg_gray << "-";
    
        // Get User's Height and Weight
        cout << con::fg_white << "\n\nEnter your " << con::fg_cyan
            << con::bg_blue << "WEIGHT" << con::fg_white << con::bg_black << "in pounds: ";
        cin >> pounds;
        cout << con::fg_white << "\n\nEnter your " << con::fg_cyan
            << con::bg_blue << "HEIGHT" << con::fg_white << con::bg_black << "... ";
        cout << "\n\tFeet: ";
        cin >> feet;
        cout << "\tInches: ";
        cin >> inches;
    
        // Make Calculatations
        inches = (feet * 12) + inches;
        meters = inches * (float)0.0254;
        kilograms = pounds / (float)2.2;
        bmi = kilograms / (meters * meters);
    
        // Display Results
        cout << "\nYou are " << con::fg_cyan << meters << "m"
            << con::fg_white << " tall.";
        cout << "\nYour mass is " << con::fg_cyan << kilograms << "kg" << con::fg_white << ".";
        cout << "\nYour Body Mass Index is " << con::fg_cyan << bmi    << con::fg_white << ".";
    
        // Return to main()?
    bmim:
        cout << "\n\nWould you like to return to the main menu? "
            << con::fg_gray << "y/n: ";
        cin >> bmireturn;
        switch (bmireturn)
        {
        case 'y':
            return;
        case 'n':
            cout << con::fg_white << "\nGood-bye!";
            break;
        default:
            cout << con::clr;
            cout << con::fg_white << "\nPlease choose y/n!";
            goto bmim;
            break;
        }
    }
    
    // Weight Loss Inline Function
    inline void weight()
    {
        using std::cout;
        using std::endl;
    
        // Clear Screen
        cout << con::clr;
    
        // Weight Loss Title
        cout << con::fg_gray << "-" << con::fg_white << "="
            << con::fg_cyan << "Weight Loss" << con::fg_white
            << "=" << con::fg_gray << "-\n\n";
        cout << con::fg_white << "Please enter your Activity level:";
        cout << con::fg_cyan << "\n\n1. " << con::fg_white << "Sedentary";
        cout << con::fg_cyan << "\n2. " << con::fg_white << "Physically active, 3+ times"
            << " a week at 60-80% of maximum heart rate";
        cout << con::fg_cyan << "\n3. " << con::fg_white << "Pregnant/nursing";
        cout << con::fg_cyan << "\n4. " << con::fg_white << "Varsity athlete or physical laborer";
        cout << "\n\nPlease make a selection: ";
        cin >> wselect;
    
        switch (wselect)
        {
        case 1:
            activity = 12;
            break;
        case 2:
            activity = 15;
            break;
        case 3:
            activity = 18;
            break;
        case 4:
            activity = 20;
            break;
        default:
            cout << con::fg_yellow << con::bg_gray << "/" << con::fg_gray << con::bg_yellow << "/"
                << con::fg_yellow << con::bg_gray << "/" << con::fg_white << con::bg_red
                << "Error: Please enter a valid choice!" << con::fg_yellow << con::bg_gray << "/"
                << con::fg_gray << con::bg_yellow << "/" << con::fg_yellow << con::bg_gray << "/\n"
                << con::fg_white << con::bg_black;
            break;
        }
    
        if (!pounds) {
            cout << con::fg_white << "\n\nEnter your " << con::fg_cyan
                << con::bg_blue << "WEIGHT" << con::fg_white << con::bg_black << "in pounds: ";
            cin >> pounds;
        }
    
        calories = activity * pounds;
        cout << con::fg_white << "\nYou need " << con::fg_cyan << calories << " calories" 
            << con::fg_white << " per day to maintain your current weight.";
        cout << con::fg_white << "\nYou need " << con::fg_cyan << (calories - 500) << " calories" 
            << con::fg_white << " per day to lose a pound a week.";
        if (wselect != 2) {
            cout << con::fg_white << "\nIf you excersized 3+ times a week, you would need "
                << con::fg_cyan << (calories - 250) << " calories" << con::fg_white
                << " per day to lose weight.";
    wmenu:
        cout << "\n\nWould you like to return to the main menu? "
            << con::fg_gray << "y/n: ";
        cin >> wreturn;
        switch (wreturn)
        {
        case 'y':
            return;
        case 'n':
            cout << con::fg_white << "\nGood-bye!";
            break;
        default:
            cout << con::clr;
            cout << con::fg_white << "\nPlease choose y/n!";
            goto wmenu;
            break;
        }
    }
    
    }
    
    // Main Menu Function
    void menu()
    {
        // Defining Menu Selection Variable
        int select;
    
        using std::cout;
        using std::endl;
    
        while (true) {
        // Main Title and Copyleft
        cout << con::clr;
        cout << con::fg_gray << "-" << con::fg_white << "="    << con::fg_cyan << "Health Fair 2005"
            << con::fg_white << "=" << con::fg_gray << "-\t(L)2005 Ty Guenley";
    
        // Menu Selection
        cout << con::fg_white << "\n\n\t::" << con::fg_gray
            << "Menu" << con::fg_white << "::";
        cout << con::fg_cyan << "\n\n1. " << con::fg_white << "Body Mass Index";
        cout << con::fg_cyan << "\n2. " << con::fg_white << "Weight Loss";
        cout << con::fg_cyan << "\n3. " << con::fg_white << "Quit";
        cout << "\n\nPlease make a selection: ";
        cin >> select;
    
        // Menu Selection Functions
        // If-Else If used to prevent recursion when functions return
        if (select == 1) {
            bmi();
        }
        else if (select == 2) {
            weight();
        }
        else if (select == 3) {
            break;
        }
        else {
            cout << con::fg_yellow << con::bg_gray << "/" << con::fg_gray << con::bg_yellow << "/"
                << con::fg_yellow << con::bg_gray << "/" << con::fg_white << con::bg_red
                << "Error: Please enter a valid choice!" << con::fg_yellow << con::bg_gray << "/"
                << con::fg_gray << con::bg_yellow << "/" << con::fg_yellow << con::bg_gray << "/\n"
                << con::fg_white << con::bg_black;
            cin.get();
        }
        }
    }
    
    int main()
    {
        menu();
        return 0;
    }
    any more tips?

    what exactly would the cin.ignore(80,'\n'); do?

    Edit: Actually, it's not QUITE working. When you choose not to go to the main menu, it goes anyways. After the break; it's returning anyways. Is there a way to keep it from returning and just terminate?
    Last edited by suzumebachi; 02-14-2005 at 02:59 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Void Functions Help
    By bethanne41 in forum C++ Programming
    Replies: 1
    Last Post: 05-09-2005, 05:30 PM
  2. Functions and Classes - What did I do wrong?
    By redmage in forum C++ Programming
    Replies: 5
    Last Post: 04-11-2005, 11:50 AM
  3. calling functions within functions
    By edd1986 in forum C Programming
    Replies: 3
    Last Post: 03-29-2005, 03:35 AM
  4. Factory Functions HOWTO
    By GuardianDevil in forum Windows Programming
    Replies: 1
    Last Post: 05-01-2004, 01:41 PM
  5. Shell functions on Win XP
    By geek@02 in forum Windows Programming
    Replies: 6
    Last Post: 04-19-2004, 05:39 AM