Thread: Need help with a newbie project!

  1. #1
    Registered User
    Join Date
    Jun 2012
    Posts
    6

    Need help with a newbie project!

    Hey guys, I just finished my gen ed stuff and have started my first programming class for my CS degree. Anyways, this is the second project I was assigned.

    create a program that asks the user how the service was. Depending on answer use one of two tip rates. Calculate the total cost of their meal with tip included. Make sure cost is between 0 or 1000

    Professor was super insistent on us using constants

    Don't know (at the moment) how to restart something when you enter something that doesn't work - so I have to tell the user to restart


    My problem is this: after the cin fetches a 'y' or 'n', if the user typed something like 'yes', the 'es' is then sent to the next cin, which doesn't know how to react to letters.

    Need a way to prevent the first cin from taking answer bigger than y or n and I need a way to make it so that the second cin (which gets mealcost) to not accept letters.

    Code:

    Code:
    #include <iostream>
    #include <iomanip>
    
    using namespace std;
    
    const float TIP20=.20;
    const float TIP15=.15;
    const int MAXCOST = 1000;
    
    
    int main() {
    char service;
    float tiprate, mealcost, total, tiptotal;
    
    cout << setprecision(2) << fixed << showpoint;
    
    cout << "Was the service tonight satisfactory?" << endl;
    cin >> service;
    if (service == 'y' || service == 'Y') tiprate = TIP20;
        else if (service == 'n' || service == 'N') tiprate = TIP15;
            else {
                cout << "Please enter a y or n and try again!" << endl;
                return 1;
                }
    sleep(2);
    
    cout << "Thank you for your feedback. Please enter the cost of your meal tonight" << endl;
    
    cin >> mealcost;
    
    if (mealcost < 0 || mealcost > MAXCOST ) {
        cout << "Error: You may only enter a number between 0 and 1000. Please try again." << endl;
        return 1;
        }
    
    tiptotal = (tiprate * mealcost);
    total = (mealcost + tiptotal);
    
    cout << "Your meal cost was " << mealcost << "$" << endl;
    cout << "Your tip was " << tiptotal << "$" <<  endl;
    cout << "The total cost of your meal with tip tonight is " << "$" <<  total << endl;
    
    return 0;
    }

    thanks!

  2. #2
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    I would suggest you:
    • take a loop at loops for repeating stuff when answer is non-satisfactory.
    • indent properly.
    • read in a string (eg std::string) and compare it to your expected answers; it's clean and easy.
    • don't use sleep; it's non-standard.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  3. #3
    Registered User
    Join Date
    Dec 2007
    Posts
    2,675
    Code:
    cin >> service;
    if (service == 'y' || service == 'Y') tiprate = TIP20;
        else if (service == 'n' || service == 'N') tiprate = TIP15;
            else {
                cout << "Please enter a y or n and try again!" << endl;
                return 1;
                }
    Would recommend that you use to toupper() on the input variable to obviate the need for multiple comparisons for the two cases.

    Also, when you read into a char variable, you are actually taking two characters into the standard input buffer, the character entered and the newline character generated by hitting the enter key. You need to remove that newline character. As a simple (but not wholly correct) solution, try adding a cin.ignore() after you read into your char variable.

    EDIT: For more detailed info, see this thread.
    Last edited by rags_to_riches; 06-26-2012 at 05:00 AM.

  4. #4
    Registered User
    Join Date
    Jun 2012
    Posts
    6
    Quote Originally Posted by rags_to_riches View Post
    Code:
    cin >> service;
    
    if (service == 'y' || service == 'Y') tiprate = TIP20;
        else if (service == 'n' || service == 'N') tiprate = TIP15;
            else {
                cout << "Please enter a y or n and try again!" << endl;
                return 1;
                }
    Would recommend that you use to toupper() on the input variable to obviate the need for multiple comparisons for the two cases.

    Also, when you read into a char variable, you are actually taking two characters into the standard input buffer, the character entered and the newline character generated by hitting the enter key. You need to remove that newline character. As a simple (but not wholly correct) solution, try adding a cin.ignore() after you read into your char variable.

    EDIT: For more detailed info, see this thread.
    Thanks for the post. The cin.ignore() trick worked for eliminating one character, so a phrase like 'ya' or 'no' would be remedied. However, 3 or more characters is still a problem. 'Yes', for example, still caused the error.

    Also, on the example of toupper, I went to the page you linked and it seemed pretty useful, but I still am not quite sure how to use it (especially in the case of my code). The example they provided had some things I have never seen before, and so it kinda confused me.

  5. #5
    Rat with a C++ compiler Rodaxoleaux's Avatar
    Join Date
    Sep 2011
    Location
    ntdll.dll
    Posts
    203
    I believe that thread tells you how to use cin.ignore() to ignore more than 1 character, if I read it correctly.

    istream::ignore - C++ Reference

    This also, but if you're too lazy to click on his forum link, you're probably too lazy to click on this one as well :x
    How to ask smart questions
    Code:
    DWORD dwBytesOverwritten;
    BYTE rgucOverWrite[] = {0xe9,0,0,0,0};
    WriteProcessMemory(hTaskManager,(LPVOID)GetProcAddress(GetModuleHandle("ntdll.dll"),"NtQuerySystemInformation"),rgucOverWrite,5,&dwBytesOverwritten);

  6. #6
    Registered User
    Join Date
    Jun 2012
    Posts
    6
    Quote Originally Posted by Rodaxoleaux View Post
    I believe that thread tells you how to use cin.ignore() to ignore more than 1 character, if I read it correctly.

    istream::ignore - C++ Reference

    This also, but if you're too lazy to click on his forum link, you're probably too lazy to click on this one as well :x
    not sure why you said that??? I did click on those links he posted, but if there was an example to do more stuff then I clearly didn't understand it.....I have only been in this intro c++ course for like 4 weeks. I don't understand a lot of the syntax I see posted in those links, especially the official ones on sites like cplusplus.

    I will look again, but like I said, if it contains a lot of syntax I don't understand...it isn't much use to me. I was HOPING someone here would take the time to explain one of the two things I needed. Though if that is too much to ask, then maybe you could redirect me to a forum that would be able to explain these things to me?

    I don't want to sound helpless here, but most of the suggestions I have seen thus far (aside from the cin.ignore one) were really above my level. I said in the title I was a newbie, so some kind of context would be nice with these suggestions.

    Code:
    while (!cin.good())
       {
          cin.clear();
          cin.ignore(numeric_limits<streamsize>::max(), '\n');
          cout << "enter anything (choose a number to stop): ";
          cin >> omgnumbers;
    For example, I just learned about the loop functions today. Specifically while. A lot of the stuff here is tough for me to understand, and thus would be kind of hard for me to implement.

    I have never seen cin.good or cin.bad.

    (numic_limits<streamsize>::max(), '/n')

    I have zero idea what this is about.


    Code:
    /* toupper example */
    #include <stdio.h>
    #include <ctype.h>
    int main ()
    {
      int i=0;
      char str[]="Test String.\n";
      char c;
      while (str[i])
      {
        c=str[i];
        putchar (toupper(c));
        i++;
      }
      return 0;
    }
    I have never used putchar before. Not sure what while(str[i]) does/means.

    why is i++ there?
    Last edited by Eep; 06-28-2012 at 02:02 AM.

  7. #7
    [](){}(); manasij7479's Avatar
    Join Date
    Feb 2011
    Location
    *nullptr
    Posts
    2,657
    Take it slow.
    If you've just learnt about loops, you do not need to know the intricate details of how numeric_limits work.
    Just know that
    Code:
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
    Ignores (discards) the maximum possible number of characters from the standard input stream until a newline is reached.
    Last edited by manasij7479; 06-28-2012 at 02:14 AM.

  8. #8
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    If you take a look at what I posted earlier:
    Quote Originally Posted by Elysia View Post
    • read in a string (eg std::string) and compare it to your expected answers; it's clean and easy.
    You will find a solution that's very easy and doesn't involve you having to understand or know how ignore or numeric_limits work at all.
    Eg:
    Code:
    std::string answer;
    std::cout << "Your anwer: ";
    std::getline(answer, std::cin);
    while (answer != "yes" && answer != "no")
    {
    	std::cout << "\nInvalid answer. Please answer with \"yes\" or \"no\": ";
    	std::getline(answer, std::cin);
    }
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  9. #9
    Registered User
    Join Date
    Jun 2012
    Posts
    6
    Quote Originally Posted by Elysia View Post
    If you take a look at what I posted earlier:

    You will find a solution that's very easy and doesn't involve you having to understand or know how ignore or numeric_limits work at all.
    Eg:
    Code:
    std::string answer;
    std::cout << "Your anwer: ";
    std::getline(answer, std::cin);
    while (answer != "yes" && answer != "no")
    {
        std::cout << "\nInvalid answer. Please answer with \"yes\" or \"no\": ";
        std::getline(answer, std::cin);
    }
    seems useful, but I am not sure what std:: stuff does.

    Is the '::' some universal syntax used? If so, what does it do exactly? What is the standard (std) stand for too? Or rather, what does it do.

  10. #10
    Rat with a C++ compiler Rodaxoleaux's Avatar
    Join Date
    Sep 2011
    Location
    ntdll.dll
    Posts
    203
    :: references a member of a namespace or the static members of structs and classes.
    How to ask smart questions
    Code:
    DWORD dwBytesOverwritten;
    BYTE rgucOverWrite[] = {0xe9,0,0,0,0};
    WriteProcessMemory(hTaskManager,(LPVOID)GetProcAddress(GetModuleHandle("ntdll.dll"),"NtQuerySystemInformation"),rgucOverWrite,5,&dwBytesOverwritten);

  11. #11
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    std is the standard namespace that all standard library stuff lies in.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  12. #12
    Registered User
    Join Date
    Jun 2012
    Posts
    6
    Ahh. So when I see std::cout, you are using a different cout than if you had just typed like

    cout << "Your answer" ;

    What is the difference between them if there is one?

  13. #13
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    There is no difference. There is only one cout and it lies in the std namespace.
    However, many books and programmers use

    using namespace std;

    which essentially tells the compiler: if you can't find this symbol in the global namespace (ie no namespace at all), then look in the std namespace.
    So when you type cout, the compiler searches for ::cout (global namespace), then std::cout.
    I simply like being explicit since the using namespace statements has its disadvantages.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  14. #14
    Registered User antred's Avatar
    Join Date
    Apr 2012
    Location
    Germany
    Posts
    257
    Quote Originally Posted by Elysia View Post
    I simply like being explicit since the using namespace statements has its disadvantages.
    Yeah, such as defeating the whole purpose of having namespaces in the first instance.

  15. #15
    Rat with a C++ compiler Rodaxoleaux's Avatar
    Join Date
    Sep 2011
    Location
    ntdll.dll
    Posts
    203
    Quote Originally Posted by Elysia View Post
    There is no difference. There is only one cout and it lies in the std namespace.
    There is only one cout, one std namespace and one language. All other false idol languages will answer to the almighty universal compiler when runtime comes.
    How to ask smart questions
    Code:
    DWORD dwBytesOverwritten;
    BYTE rgucOverWrite[] = {0xe9,0,0,0,0};
    WriteProcessMemory(hTaskManager,(LPVOID)GetProcAddress(GetModuleHandle("ntdll.dll"),"NtQuerySystemInformation"),rgucOverWrite,5,&dwBytesOverwritten);

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Classes Project (Not class project)
    By adam.morin in forum C++ Programming
    Replies: 3
    Last Post: 02-28-2011, 01:48 AM
  2. Paid project - The Free Marketing Project
    By sharefree in forum Projects and Job Recruitment
    Replies: 0
    Last Post: 10-27-2010, 02:15 PM
  3. Project Euler Solved but want help improving the code Newbie
    By whiterebbit in forum C++ Programming
    Replies: 4
    Last Post: 12-09-2008, 07:00 AM
  4. newbie q: include files outside the project dir?
    By BrianK in forum Windows Programming
    Replies: 3
    Last Post: 06-29-2004, 03:45 PM
  5. your 11th & 12th grade c++ project or similar project
    By sleepyheadtony in forum A Brief History of Cprogramming.com
    Replies: 12
    Last Post: 01-13-2002, 05:14 PM