Functions Problem
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 21

Thread: Functions Problem

  1. #1
    Join Date
    Nov 2009
    Posts
    8

    Exclamation Functions Problem

    I'm having trouble with this homework problem. I know I'm close to having it solved but I can't get the loop to stop. It finds the correct name to the parking sticker in the text file but keeps looping over and over. Here's the problem for a better understanding:

    Assume that a file named HWK5.txt has a single name (last name only -- no first name or middle initial) and a parking sticker number (6 digits) on each line of the file. It is unknown how many names are on the file. (You will need to make up a test file to use.) Write a program that will ask the user for a parking sticker number (000000 to stop) and then search the file for that number. When it finds the number in the file, it will write out "This parking sticker belongs to " followed by the corresponding name on the file, or if the sticker number is not found on the file, the message "This parking sticker is not on file. Try again." should be displayed. The program will then ask for another sticker number and repeat until a sticker number of 000000 (or just plain zero) is entered. To perform the search, the parking sticker number should be sent to a function called findName, which you will write. The function findName should open the file HWK5.txt, search it for the given sticker number, and return the corresponding name to the calling program. Before it returns, the function should close the file HWK5.txt so that it will be ready to be used for the next search. If the sticker number is not found on the file, the function should return a value of "NOT FOUND" to the calling program. The function should NOT display anything on the screen; the main function should handle this task, as well as prompting for the next sticker number.

    I'm not understanding the bold portion of the problem and in turn is probably what is causing my trouble. Here is the work I have so far:

    #include <iostream>
    #include <fstream>
    #include <string>
    using namespace std;

    int main()
    {
    string lastName;
    double number, target, parkingSticker;
    const double SENTINEL = 000000;

    cout << "Please enter a parking sticker number (enter 000000 to exit): " << endl;
    cin >> target;

    while (target != SENTINEL)
    {
    ifstream input("HWK5.txt");
    if (input.is_open())
    {
    while (! input.eof())
    {
    input >> lastName >> parkingSticker;
    if (target == parkingSticker)
    cout << "The parking sticker number belongs to " << lastName << endl;
    else
    cout << "This parking sticker is not on file. Try again." << endl;
    }
    }
    input.close();
    }
    system("pause");
    return 0;
    }

    The function is working correctly as far as finding the correct name to the parking sticker number. It just displays:

    The parking sticker number belongs to Smith
    This parking sticker is not on file. Try again.
    The parking sticker number belongs to Smith
    This parking sticker is not on file. Try again.
    The parking sticker number belongs to Smith
    This parking sticker is not on file. Try again.
    ::repeats this over and over::

    Just wondering how I'm suppose to stop it from looping over and over and not display the second message if it actually finds the parking sticker number. Any help would be greatly appreciated.

  2. #2
    Join Date
    Nov 2009
    Posts
    8

    Re: Functions Problem

    Code:
    #include <iostream>
    #include <fstream>
    #include <string>
    using namespace std;
    
    int main()
    {
        string lastName;
        double number, target, parkingSticker;
        const double SENTINEL = 000000;
        
        cout << "Please enter a parking sticker number (enter 000000 to exit): " << endl;
        cin >> target;
        
        while (target != SENTINEL)
        {
              ifstream input("HWK5.txt");
              if (input.is_open())
              {
                 while (! input.eof())
                 {
                       input >> lastName >> parkingSticker;
                       if (target == parkingSticker)
                          cout << "The parking sticker number belongs to " << lastName << endl;
                       else
                          cout << "This parking sticker is not on file. Try again." << endl;
                 }
              }
              input.close();
        }
        system("pause");
        return 0;
    }
    A better view of the code I have so far.

  3. #3
    Join Date
    Jan 2004
    Location
    Düsseldorf, Germany
    Posts
    2,401

    Re: Functions Problem

    The bold part of the assignment means, you should write a function like this:
    Code:
    std::string find(const std::string& sticker) {
      // open file
      // search file for sticker
      // if found, return lastname
      // if not found, return "NOT FOUND"
    }
    In turn, your main function should be reduced to:
    Code:
    int main()
    {
        const double SENTINEL = 000000;
    
        for (;;) {    
            std::cout << "Please enter a parking sticker number (enter 000000 to exit): " << std::endl;
            std::cin >> target;
            if (target == SENTINEL) break;    
            std::cout << find(target) << std::endl;
        }
    }
    About your current code. A typical mistake is the following:
    Code:
                 while (! input.eof())
                 {
                       input >> lastName >> parkingSticker;
    input.eof() is only set after the end of file has been read, so your program will execute the loop one time too many. Instead, use the following:
    Code:
    while (input >> lastName >> parkingSticker) {
    Another thing: How many times should the user be asked for a sticker number and how often is he asked in your program?
    More computing sins are committed in the name of efficiency (without necessarily achieving it) than for any other single reason - including blind stupidity. --W.A.Wulf

    Premature optimization is the root of all evil --Donald E. Knuth


    Please read Information on posting before posting, especially the info on using [code] tags.

  4. #4
    Join Date
    May 2009
    Posts
    2,413

    Re: Functions Problem

    Just a note. It's generally not a very good idea to compare floats and doubles for equality using ==.

  5. #5
    Join Date
    Jan 2004
    Location
    Düsseldorf, Germany
    Posts
    2,401

    Re: Functions Problem

    Quote Originally Posted by nuzzle View Post
    Just a note. It's generally not a very good idea to compare floats and doubles for equality using ==.
    True and the parking sticker should be neither one nor an int. It should be a string !!
    More computing sins are committed in the name of efficiency (without necessarily achieving it) than for any other single reason - including blind stupidity. --W.A.Wulf

    Premature optimization is the root of all evil --Donald E. Knuth


    Please read Information on posting before posting, especially the info on using [code] tags.

  6. #6
    Join Date
    Nov 2009
    Posts
    8

    Re: Functions Problem

    Thanks guys for the responses but I'm still not getting this so I asked for help from my professor. This is what he had to say:

    The variable parkingSticker should be declared a double, not a string. You should also have the while loop for the sentinel as the outside loop, not the inside loop. The sentinel-controlled loop should have everything else in it, including the open and close commands. The loop on file input should (which is end-of-file controlled) should keep comparing the target to the parkingSticker until either you reach the target or hit the end of the file. You will need some bool variable to set so that you know you have found the target and can quit looking.
    I have had parkingSticker declared as a double and I switched the while loop to be the outside one. This was all done before I made this thread. Guess what I'm having trouble with is the bool variable thing. I just can't get the loop to stop looking after it's already found. Anymore help would be greatly appreciated.

  7. #7
    Join Date
    Jan 2004
    Location
    Düsseldorf, Germany
    Posts
    2,401

    Re: Functions Problem

    Some hints:
    Code:
        while (target != SENTINEL)
    The condition for your while loop compares target and SENTINEL. Neither one of the variable is changed inside the while loop. Thus the loop, if entered, does not have a possibility to terminate.
    Code:
                 while (! input.eof())
                 {
                       input >> lastName >> parkingSticker;
                       if (target == parkingSticker)
                          cout << "The parking sticker number belongs to " << lastName << endl;
                       else
                          cout << "This parking sticker is not on file. Try again." << endl;
                 }
    The while loop iterates (wrongly as I pointed out earlier) over each line of the file. Thus a line is printed out for each line in the search file. But what you actually want is first to search through the file and after you are done, print a line if the search was successful or not.
    More computing sins are committed in the name of efficiency (without necessarily achieving it) than for any other single reason - including blind stupidity. --W.A.Wulf

    Premature optimization is the root of all evil --Donald E. Knuth


    Please read Information on posting before posting, especially the info on using [code] tags.

  8. #8
    Join Date
    Jan 2004
    Location
    Düsseldorf, Germany
    Posts
    2,401

    Re: Functions Problem

    Quote Originally Posted by Ruined Embrace View Post
    This is what he had to say:
    Quote Originally Posted by professor
    The variable parkingSticker should be declared a double, not a string.
    Ask him why! So you can divide two parking sticker numbers by each other? Or so that the square root of one parking sticker results in another parking sticker? Or is it just to ensure that comparing two parking sticker numbers does not necessarily return the correct result. Maybe there's a relationship between the gravity of a planet and a parking sticker number? I'll be intrigued to know...
    More computing sins are committed in the name of efficiency (without necessarily achieving it) than for any other single reason - including blind stupidity. --W.A.Wulf

    Premature optimization is the root of all evil --Donald E. Knuth


    Please read Information on posting before posting, especially the info on using [code] tags.

  9. #9
    Join Date
    Apr 1999
    Posts
    27,433

    Re: Functions Problem

    Quote Originally Posted by Ruined Embrace View Post
    The variable parkingSticker should be declared a double, not a string
    Sometimes, I wonder where in the world these teachers are coming from.

    Just wondering how I'm suppose to stop it from looping over and over and not display the second message if it actually finds the parking sticker number.
    This is trivial. Just make your while loop only execute if a ticket is not found.
    Code:
    bool foundTicket = false;
    while (I have stuff to input && !foundTicket )
    {
        if ( I've found a ticket )
        {
            do stuff when ticket is found
            Now set foundTicket to the right value to stop the loop
        }         
    }
    Regards,

    Paul McKenzie

  10. #10
    Join Date
    Nov 2009
    Posts
    8

    Re: Functions Problem

    Quote Originally Posted by treuss View Post
    Some hints:
    Code:
        while (target != SENTINEL)
    The condition for your while loop compares target and SENTINEL. Neither one of the variable is changed inside the while loop. Thus the loop, if entered, does not have a possibility to terminate.
    I have to keep everything in that. I have to give the user a way to exit the program and that's by the SENTINEL value. I'm still trying to figure out this boolean thing. I graduated a two year school with over a 3.0 GPA and I've never had a subject this hard. The book is not user friendly at all and the teacher is horrible. I've sat on this project for 3 hours every night trying to figure it out. Here it is, a week past due and I'm not even sure he'll accept it when I get finished. There's no example even close to this project in the book. Hell, reading from a text file isn't even in this book until Chapter 13 and we just now got to Chapter 7 in class.

  11. #11
    Join Date
    Apr 1999
    Posts
    27,433

    Re: Functions Problem

    Quote Originally Posted by Ruined Embrace View Post
    I have to keep everything in that.
    I don't know what that's supposed to mean.
    I have to give the user a way to exit the program and that's by the SENTINEL value. I'm still trying to figure out this boolean thing.
    Did you read my post? Without giving you the code verbatim, it should have answered your question.
    Also, I graduated a two year school with over a 3.0 GPA and I've never had a subject this hard.
    What subjects? Was your major based on cold logical reasoning (as computer programming and computer science is) or on some other criteria? Some brilliant people who excel in other topics can't for the life of them write a computer program -- it has nothing to do with intelligence, their brains are just not wired to follow or devise a set series of steps (i.e. algorithm).
    The book is not user friendly at all
    What is the name of the book? You know that this is your opinion -- the book may not be user-friendly to you, but may be a piece of cake to someone else.

    Regards,

    Paul McKenzie

  12. #12
    Join Date
    Nov 2009
    Posts
    8

    Re: Functions Problem

    Think I'm pretty close to solving this now. Anymore help would be greatly appreciated.

    Code:
    #include <iostream>
    #include <fstream>
    #include <string>
    using namespace std;
    
    int main()
    {
        string lastName;
        double number, target, parkingSticker;
        const double SENTINEL = 000000;
        
        cout << "Please enter a parking sticker number (enter 000000 to exit): " << endl;
        cin >> target;
        
        while (target != SENTINEL)
        {
              bool found = false;
              string foundName = "NOT FOUND";
              
              ifstream input("HWK5.txt");
              if (input.is_open())
              {
                 
                 input >> lastName >> parkingSticker;
                 while (! input.eof() && !found)
                 {
                       if (target == parkingSticker)
                       {
                          foundName = lastName;
                          found = true;
                       }
                 }
              }
              input.close();
              return foundName;
        }
        if (lastName != "NOT FOUND")            
           cout << "The parking sticker number belongs to " << lastName << endl;
        else
           cout << "This parking sticker is not on file. Try again." << endl;
                  
        system("pause");
        return 0;
    }

    I'm getting an error on the "return foundName;" part. It's telling me that it can't convert string to integer. I have to return something though. Think that's the only part that's holding me back.
    Last edited by Ruined Embrace; November 6th, 2009 at 02:37 PM.

  13. #13
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Fairfax, VA
    Posts
    10,891

    Re: Functions Problem

    Since you're in main(), there's no point in returning anything other than 0.

    Also, you still are never modifying target within the while loop; thus the loop can never end once it is entered.

  14. #14
    Join Date
    Jan 2004
    Location
    Düsseldorf, Germany
    Posts
    2,401

    Re: Functions Problem

    You stated in your first post that the exercise involves
    Quote Originally Posted by Ruined Embrace View Post
    a function called findName, which you will write
    I still don't see any function in your code. The function will make your code easier, not more complex, so it is time to get it in. Do it. Now.
    More computing sins are committed in the name of efficiency (without necessarily achieving it) than for any other single reason - including blind stupidity. --W.A.Wulf

    Premature optimization is the root of all evil --Donald E. Knuth


    Please read Information on posting before posting, especially the info on using [code] tags.

  15. #15
    Join Date
    Nov 2009
    Posts
    8

    Re: Functions Problem

    Code:
    #include <iostream>
    #include <fstream>
    #include <string>
    using namespace std;
    
    int main()
    {
        string lastName;
        double number, target, parkingSticker;
        const double SENTINEL = 000000;
        
        cout << "Please enter a parking sticker number (enter 000000 to exit): " << endl;
        cin >> target;
        
        while (target != SENTINEL)
        {
              string findName(int foundName)
              {
                 bool found = false;
                 string foundName = "NOT FOUND";
              
                 ifstream input("HWK5.txt");
                 if (input.is_open())
                 {
    
                     input >> lastName >> parkingSticker;             
                     while (! input.eof() && !found)
                     {
                         if (target == parkingSticker)
                         {
                             foundName = lastName;
                             found = true;
                         }
                       input >> lastName >> parkingSticker;                     
                     }
                 }
              input.close();
              return foundName;
              }
        }
        if (foundName != "NOT FOUND")            
           cout << "The parking sticker number belongs to " << lastName << endl;
        else
           cout << "This parking sticker is not on file. Try again." << endl;
                  
        system("pause");
        return 0;
    }


    Still many problems.

Page 1 of 2 12 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center