CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 13 of 13
  1. #1
    Join Date
    Apr 2013
    Posts
    42

    Can't read in a text file to load a struc

    Hi,
    I am doing an exercise that reads in a text file and loads the data into a struct. My problem is it doesn't read anything from the text file. I think it's the way I'm loading the data. Oh, it does read in the first record that tells the program how many contributor records to create, but nothing after that. Here it is:

    Code:
    //
    #include <iostream>
    #include <fstream>
    #include <cstdlib>
    const int strsize = 30;
    const int SIZE = 60;
    
    struct contributions {
        char fullname[strsize]; //name
        double donation;        //donation
    };
    
    int main()
    {
        using namespace std;
    
        char filename[SIZE];
        ifstream inFile;        // object for handling file input
    
        cout << "Enter name of data file: ";
        cin.getline(filename, SIZE);
        inFile.open(filename);  // associate inFile with a file
        if (!inFile.is_open())  // failed to open file
        {
            cout << "Could not open the file " << filename << endl;
            cout << "Program terminating.\n";
            // cin.get();    // keep window open
            exit(EXIT_FAILURE);
        }
    
        int howmany = 0;
    
    //   cout << "What's the number of contributions?: ";
        inFile >> howmany;
        int count = 0;
        contributions * ps = new contributions[howmany];
    
        while (count < howmany)
        {
          inFile.get(ps[count].fullname, strsize);
          inFile.get();
          inFile >> ps[count].donation;
          inFile.get();
    
          cout << "fullname: " << ps[count].fullname << "\n";
          cout << "donation: " << ps[count].donation << "\n";
    
          count++;
        }
    
        if (inFile.eof())
            cout << "End of file reached.\n";
        else if (inFile.fail())
            cout << "Input terminated by data mismatch.\n";
        else
            cout << "Input terminated for unknown reason.\n";
        if (count == 0)
            cout << "No data processed.\n";
        else
        {
            cout << "Items read: " << count << endl;
            //cout << "Sum: " << sum << endl;
            //cout << "Average: " << sum / count << endl;
        }
        inFile.close();
    
        cout << "Please enter one of the following choices:\n";
        cout << "a. Patrons\t" << "b. Grand Patrons\n";
        cout << "q. quit\n";
        cout << "Enter  choice ";
        int numdon;
        char choice;
        cin >> choice;
        while (choice != 'Q' && choice != 'q')
        {
            switch(choice)
            {
                case 'a':
                case 'A':
                        count = 0;
                        numdon = 0;
                        cout << "\tPatrons \n";
                        while (count < howmany)
                           {
                           if (ps[count].donation < 10000)
                             {
                             cout << ps[count].fullname << "\t" << ps[count].donation << "\n";
                             numdon++;
                             }
                             count++;
                           }
                           if (numdon == 0)
                             cout << "None\a\n";
                          break;
                case 'b':
                case 'B':
                        count = 0;
                        numdon = 0;
                        cout << "\tGrand Patrons \n";
                        while (count < howmany)
                           {
                           if (ps[count].donation >= 10000)
                             {
                             cout << ps[count].fullname << "\t" << ps[count].donation << "\n";
                             numdon++;
                             }
                             count++;
                           }
                           if (numdon == 0)
                             cout << "None\a\n";
                            break;
    
                default : cout << "Enter a valid choice.\n";
             }
             cout << "Next choice: ";
             cin >> choice;
         }
    
        cin.get();
        cin.get();
        return 0;
    }
    Here is the record input:

    Data file:
    4
    Suz Stuz
    55000
    Froco Frock
    5000
    Yandi Yuck
    100500
    Dippy Dip
    120000

    9 records - each struct has two members; full name and donation.
    First record should be number of contributors

    Thanks in advance

  2. #2
    Join Date
    Aug 2000
    Location
    West Virginia
    Posts
    7,721

    Re: Can't read in a text file to load a struc

    You have ...

    Code:
    inFile >> howmany;
    
    // ...
    
    inFile.get(ps[count].fullname, strsize);
    after reading in howmany, the '\n' is still in the input stream.
    So the "get" reads an empty record. You need to get rid of the
    '\n' from the first input.

    Code:
    inFile >> howmany;
    inFile.ignore(1000,'\n');  // add this line
    Is there a reason you are using "get" in the loop, instead of getline() ?

  3. #3
    Join Date
    Apr 1999
    Posts
    27,449

    Re: Can't read in a text file to load a struc

    Quote Originally Posted by FenixRising View Post
    Hi,
    I am doing an exercise that reads in a text file and loads the data into a struct.
    In addition,

    1) Your program has a memory leak. You failed to delete[] the memory you allocated with new[].

    2) You should check if the number you read in is >= 0. Otherwise your program will go haywire with a negative number.

    Regards,

    Paul McKenzie

  4. #4
    Join Date
    Apr 2013
    Posts
    42

    Re: Can't read in a text file to load a struc

    Philip:

    No reason for the get instead of getline. I meant to use getline. There are now two more issues (after I made your recommended changes). The donations figures are different in the struc after reading and loading them. And, I get an close error on the close file.

    donations are (starting at the top):

    5000
    0
    500
    20000


    Error message is: Input terminated for unknown reason (see program)

    Thnx

    Paul:

    Thanks for the input. I'll make suggested changes.

  5. #5
    Join Date
    Aug 2000
    Location
    West Virginia
    Posts
    7,721

    Re: Can't read in a text file to load a struc

    You might need to post your current code for reading the file.

    Did you change the first get() to getline() in the loop ? If so, you
    should remove the first get() in your loop (since getline reads
    and discards the '\n')

    Code:
    inFile.getline(ps[count].fullname,strsize);
    //  inFile.get();

  6. #6
    2kaud's Avatar
    2kaud is online now Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,824

    Re: Can't read in a text file to load a struc

    Error message is: Input terminated for unknown reason (see program)
    Correct! If you debug your program you'll easily find out why you always get this message. Hint. Look at the conditions you are using around inFile.eof() and inFile.fail().

    Why not have fullname as a string in structure contributions rather than a char array? Using getline as suggested previously I read the contributions correctly. If you are getting the wrong values displayed then again you need to debug your program to establish the problem. Note that infile >> xxxx still leaves the trailing newline in the buffer as already mentioned together with the solution.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  7. #7
    Join Date
    Apr 2013
    Posts
    42

    Re: Can't read in a text file to load a struc

    Hi,

    I made the correction to the commenting out the inFile.get() line after the inFile.getline(<code>). And, that solved the problem of the invalid contributions being read in. Now, the only problem I still have is the invalid eof of the text file. I'm posting the new code. And, the error message is: Input terminated for unknown reason(See program). I looked at the code (which has worked in other programs) and don't see anything wrong.

    Code:
    #include <iostream>
    #include <fstream>
    #include <cstdlib>
    const int strsize = 30;
    const int SIZE = 60;
    
    struct contributions {
        char fullname[strsize]; //name
        double donation;        //donation
    };
    
    int main()
    {
        using namespace std;
    
        char filename[SIZE];
        ifstream inFile;        // object for handling file input
    
        cout << "Enter name of data file: ";
        cin.getline(filename, SIZE);
        inFile.open(filename);  // associate inFile with a file
        if (!inFile.is_open())  // failed to open file
        {
            cout << "Could not open the file " << filename << endl;
            cout << "Program terminating.\n";
            // cin.get();    // keep window open
            exit(EXIT_FAILURE);
        }
    
        int howmany = 0;
    
     //   cout << "What's the number of contributions?: ";
        inFile >> howmany;
        inFile.ignore(1000,'\n');
    
        int count = 0;
        contributions * ps = new contributions[howmany];
    
        while (count < howmany)
        {
          inFile.getline(ps[count].fullname, strsize);        //
          //inFile.get();
          inFile >> ps[count].donation;
          inFile.get();
    
          cout << "fullname: " << ps[count].fullname << "\n";
          cout << "donation: " << ps[count].donation << "\n";
    
          count++;
        }
    
        if (inFile.eof())
            cout << "End of file reached.\n";
        else if (inFile.fail())
            cout << "Input terminated by data mismatch.\n";
        else
            cout << "Input terminated for unknown reason.\n";
        if (count == 0)
            cout << "No data processed.\n";
        else
        {
            cout << "Items read: " << count << endl;
            //cout << "Sum: " << sum << endl;
            //cout << "Average: " << sum / count << endl;
        }
        inFile.close();
    
        cout << "Please enter one of the following choices:\n";
        cout << "a. Patrons\t" << "b. Grand Patrons\n";
        cout << "q. quit\n";
        cout << "Enter  choice ";
        int numdon;
        char choice;
        cin >> choice;
        while (choice != 'Q' && choice != 'q')
        {
            switch(choice)
            {
                case 'a':
                case 'A':
                        count = 0;
                        numdon = 0;
                        cout << "\tPatrons \n";
                        while (count < howmany)
                           {
                           if (ps[count].donation < 10000)
                             {
                             cout << ps[count].fullname << "\t" << ps[count].donation << "\n";
                             numdon++;
                             }
                             count++;
                           }
                           if (numdon == 0)
                             cout << "None\a\n";
                          break;
                case 'b':
                case 'B':
                        count = 0;
                        numdon = 0;
                        cout << "\tGrand Patrons \n";
                        while (count < howmany)
                           {
                           if (ps[count].donation >= 10000)
                             {
                             cout << ps[count].fullname << "\t" << ps[count].donation << "\n";
                             numdon++;
                             }
                             count++;
                           }
                           if (numdon == 0)
                             cout << "None\a\n";
                            break;
    
                default : cout << "Enter a valid choice.\n";
             }
             cout << "Next choice: ";
             cin >> choice;
         }
        delete ps;
        cin.get();
        cin.get();
        return 0;
    }
    Thnx

  8. #8
    GCDEF is offline Elite Member Power Poster
    Join Date
    Nov 2003
    Location
    Florida
    Posts
    12,635

    Re: Can't read in a text file to load a struc

    Again, learn to use the debugger and it will be obvious.

    You have an unconditional else statement checking the file status.

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

    Re: Can't read in a text file to load a struc

    Quote Originally Posted by FenixRising View Post
    Hi,

    I made the correction to the commenting out the inFile.get() line after the inFile.getline(<code>). And, that solved the problem of the invalid contributions being read in. Now, the only problem I still have is the invalid eof of the text file.
    Continuing with my post:
    Code:
     delete ps;
    Should be:
    Code:
     delete [] ps;
    As to your issue now, what if there are more items than was stated on the first line of the file? In other words, you haven't reached the end-of-file, and the last read didn't fail.

    Regards,

    Paul McKenzie

  10. #10
    2kaud's Avatar
    2kaud is online now Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,824

    Re: Can't read in a text file to load a struc

    Input terminated for unknown reason(See program)
    Code:
    if (inFile.eof())
            cout << "End of file reached.\n";
        else if (inFile.fail())
            cout << "Input terminated by data mismatch.\n";
        else
            cout << "Input terminated for unknown reason.\n";
    What happens if not eof and not fail?

    I suspect you have extra chars at the end of your data file so when you have read your 4 data items you're not actually at end of file.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  11. #11
    Join Date
    Apr 2013
    Posts
    42

    Re: Can't read in a text file to load a struc

    Hi,
    I have resolved my last issue by removing two blank records in the input file. Thnx to everyone for the help.

  12. #12
    GCDEF is offline Elite Member Power Poster
    Join Date
    Nov 2003
    Location
    Florida
    Posts
    12,635

    Re: Can't read in a text file to load a struc

    Quote Originally Posted by FenixRising View Post
    Hi,
    I have resolved my last issue by removing two blank records in the input file. Thnx to everyone for the help.
    I wouldn't say you resolved it as much as you swept it under the rug.

  13. #13
    2kaud's Avatar
    2kaud is online now Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,824

    Re: Can't read in a text file to load a struc

    Quote Originally Posted by FenixRising View Post
    Hi,
    I have resolved my last issue by removing two blank records in the input file. Thnx to everyone for the help.
    No, you haven't fixed the problem. What you have done is alter the data to make it work with your incorrect code logic. Your program still has the same incorrect code!
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

Posting Permissions

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





Click Here to Expand Forum to Full Width

Featured