GIDForums  

Go Back   GIDForums > Computer Programming Forums > C++ Forum
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 19-Feb-2008, 21:12
Mr_Peepers Mr_Peepers is offline
New Member
 
Join Date: Feb 2008
Posts: 18
Mr_Peepers is on a distinguished road

I/O array problem with data files


Currently I need to read data from a file, such like this

Measurements for Lansing, Michigan during April, 2000
63 32 0.00
54 43 0.10
59 39 0.00
46 24 0.00
52 20 0.00
54 30 0.00

The first line is obviously disregarded, since all we want are the numbers.

limitations are simply use arrays, no vectors.

I had something like this for now, though I'm not sure if it cuts the first line out or not...I'm also cutting main() off the post, I know it works, its the I/O I don't get.

CPP / C++ / C Code:
      void read( ifstream& In, ReadData List[], int Size, int& Num )
      {
        ReadData Temp;
 
        Num = 1;
       
        for (;;)
        {
          In >> Temp.Min >> Temp.Max >> Temp.Precipt;
       
          if (In.fail() || Num >= Size) break;
       
          List[Num] = Temp
       
          Num++;
        }
      }
 
      void process( const ReadData List[], int Num )
      {
        int I;
        //***************************
        // Display the column headers
        //***************************
       
        cout << "\n";
        cout << "Minimum Value      Maximum Value     Precipitation\n";
        cout << "-------------      -------------     -------------\n";
       
        for(I=0;I<Num;I++)
        {
          cout << resetiosflags( ios::right ) << setiosflags( ios::left );
          cout << setw(20) << List[i].Min << "          "<< List[i].Max << "          "<< List[i].Precipt <<endl;
        }
      }

declaring the struct is
CPP / C++ / C Code:
      struct ReadData
      {
        int Min,Max;
        double Precipt;
      };

Currently the output yeilds
0 0 (some reference address)

...and thats it

I know i'm somewhere close, but I'm drawing a blank. I set Num = 1 in hopes of skipping the first set in the data, which would be the string of words

How do i fix the array so it yields the correct I/O?

Your help is greatly appreciated
  #2  
Old 19-Feb-2008, 22:06
WaltP's Avatar
WaltP WaltP is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Midwest US
Posts: 3,373
WaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to all

Re: I/O array problem with data files


To skip the first line of the data file, use getline().

Then, always display what was read immediately after reading it to make sure the read worked properly.
__________________

The 3 Laws of the Procrastination Society:
1) Never do today that which can be put off until tomorrow
2) Tomorrow never comes
  #3  
Old 20-Feb-2008, 06:26
davis
 
Posts: n/a

Re: I/O array problem with data files


Quote:
Originally Posted by WaltP
Then, always display what was read immediately after reading it to make sure the read worked properly.

Mr_Peepers, you'll note that WaltP is absolutely fascinated with printf/cout...

If you use the C++ streaming library functions properly, you don't need couts littering your code. All you have to do is check that the ios::good bit is set after a read. That means that "the read worked properly."

Here's a simple example:

CPP / C++ / C Code:
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
    cout << "Enter the filename containing data to be read: ";
    string filename;
    getline( cin, filename );
    ifstream infile( filename.c_str() );
    if( infile.is_open() )
    {
        int x;
        while( infile.good() )
        {
            infile >> x;
            if( infile.good() )
            {
                cout << "Read " << x << endl;
            }
            else
            {
                if( infile.fail() )
                {
                    cout << "fail flag set" << endl;
                }
                if( infile.eof() )
                {
                    cout << "eof flag set" << endl;
                }
                if( infile.bad() )
                {
                    cout << "bad flag set" << endl;
                }
                cout << "Error reading from stream opened on file named " << filename << endl;
            }
        }
        infile.close();
    }
    return 0;
}


Output:

Code:
Enter the filename containing data to be read: /tmp/foo.txt Read 1 Read 2 Read 3 fail flag set Error reading from stream opened on file named /tmp/foo.txt $ cat /tmp/foo.txt 1 2 3 ABC

Note how the contents of foo are organized. The read tries to convert to an integer in the loop. Since the first three conversions are successful, the output is as expected and "x" is "happy" each time through. When the input stream encounters data that can not be converted to "x," we get a fail bit set.

Here's the code that does the work that you want to do, without a bunch of silly "displays" of the read activities...always is a fairly hefty requirement, huh?!

Of course, I didn't use an array, but I didn't use a vector, either. I used dynamic memory allocation and a series of linked data structures in a very abbreviated "linked list" fashion.

CPP / C++ / C Code:
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

typedef struct st_data
{
    int             x;
    int             y;
    float           f;
    struct st_data* next;
} DATA;

int main()
{
    DATA* p_data    = new DATA();
    DATA* p_tmp     = NULL;
    DATA data;
    unsigned int ui = 0;

    cout << "Enter the filename containing data to be read: ";
    string filename;
    getline( cin, filename );
    ifstream infile( filename.c_str() );
    if( infile.is_open() )
    {
        getline( infile, filename ); // skip the first line
        while( infile.good() )
        {
            infile >> data.x >> data.y >> data.f;
            if( infile.good() )
            {
                ++ui;
                p_tmp = p_data;
                if( ui != 1 ) // not at list head node
                {
                    while( p_tmp->next != NULL ) // get to the end of the list
                    {
                        p_tmp = p_tmp->next;
                    }
                    p_tmp->next = new DATA(); // add a new node
                    p_tmp->next->x = data.x; // copy the data
                    p_tmp->next->y = data.y;
                    p_tmp->next->f = data.f;
                    p_tmp->next->next = NULL;
                }
                else
                {
                    p_tmp->x = data.x;
                    p_tmp->y = data.y;
                    p_tmp->f = data.f;
                    p_tmp->next = NULL;
                }
            }
        }
        infile.close();
        cout << "Read " << ui << " data chunks " << endl; // user feedback
    }

    if( ui > 0 ) // print the data
    {
        p_tmp = p_data;
        while( p_tmp != NULL )
        {
            cout << p_tmp->x << " " << p_tmp->y << " " << p_tmp->f << endl;
            p_tmp = p_tmp->next;
        }
    }

    while( p_data->next != NULL )
    {
        p_tmp = p_data->next;
        delete p_data;
        p_data = p_tmp;
    }
    delete p_data;

    return 0;
}


Output:

Code:
Enter the filename containing data to be read: /tmp/data.txt Read 6 data chunks 63 32 0 54 43 0.1 59 39 0 46 24 0 52 20 0 54 30 0

Code:
==4626== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 16 from 1) --4626-- --4626-- supp: 16 Ubuntu-stripped-ld.so ==4626== malloc/free: in use at exit: 0 bytes in 0 blocks. ==4626== malloc/free: 20 allocs, 20 frees, 9,072 bytes allocated. ==4626== ==4626== All heap blocks were freed -- no leaks are possible.

...you may want to add iomanip to your include directives.

Also, if you add lines to your data file (I copied the same data and pasted it several times in the file to "grow" it significantly):

Code:
Enter the filename containing data to be read: /tmp/data.txt Read 2184 data chunks 63 32 0 54 43 0.1 59 39 0 46 24 0

...the code should continue to work.

Code:
==4865== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 16 from 1) --4865-- --4865-- supp: 16 Ubuntu-stripped-ld.so ==4865== malloc/free: in use at exit: 0 bytes in 0 blocks. ==4865== malloc/free: 4,376 allocs, 4,376 frees, 141,930 bytes allocated. ==4865== ==4865== All heap blocks were freed -- no leaks are possible.

...of course, once you run out of memory, the code will fail and the "leak" will not be cleaned up. But that's another topic...


:davis:
  #4  
Old 20-Feb-2008, 14:23
Mr_Peepers Mr_Peepers is offline
New Member
 
Join Date: Feb 2008
Posts: 18
Mr_Peepers is on a distinguished road

Re: I/O array problem with data files


Thanks Davis, That really seemed to help fix reading and outputting.

I should have mentioned, with that data, some things need to be calculated, namely average x, y, and z values, and simple searches to find the smallest and largest numbers.

So with this allocation method, average for x would go something like this?

CPP / C++ / C Code:
while ( p_tmp != NULL )
  {
    total += p_tmp-> x;
    count += 1;
    p_tmp = p_tmp -> next;
  }

having of course declared total and count, with average being total / count.
  #5  
Old 20-Feb-2008, 17:03
WaltP's Avatar
WaltP WaltP is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Midwest US
Posts: 3,373
WaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to all

Re: I/O array problem with data files


Quote:
Originally Posted by davis
Mr_Peepers, you'll note that WaltP is absolutely fascinated with printf/cout...
And Dave has never mentioned them. Hmmm....
__________________

The 3 Laws of the Procrastination Society:
1) Never do today that which can be put off until tomorrow
2) Tomorrow never comes
  #6  
Old 21-Feb-2008, 07:51
davis
 
Posts: n/a

Re: I/O array problem with data files


Quote:
Originally Posted by WaltP
And Dave has never mentioned them. Hmmm....

Spoken like a true, self-proclaimed expert with over 30 years of programming experience...that is, accept no responsibility for what you post. Redirect away from yourself. Completely discount that you said "always" because Dave has "never not" mentioned using printf/cout.

Why not celebrate an option to using printf/cout?! Do you feel that their presence in your own code really help you more than hurt you? How many times have you needlessly typed printf or cout followed by some string constants and data members? That time couldn't be better utilized? How many hours over the supposedly 30+ years might you have saved by employing alternatives that also "live well" in "release" code? How much time did you spend taking OUT the spew to console statements? How much time did you waste putting them in the WRONG places? Hey, you're the expert. Who are the rest of us simpletons to be suggesting that you are not the commander of your own destiny and that we mere mortals should grovel at every opportunity to partake in the blessings of coding prophecy offered by the truly Outstanding Member (graded solely on quantity, not quality) found in the glorious visionage encountered here as WaltP?

How long ago was it that you were some kind of prince entering some buildings and your fairy tale wonderland of C++ was a dark place where, with a little C knowledge, you could somehow "see" your way around a bit?

Remember how that started? Gather 'round children, and I'll tell you a story.

...you somehow promote yourself to "adult" status and everyone else to "children." Who was the "young prince?" By your story, he was well-versed in the art of C...that seems to imply that you meant yourself.

Maybe you are the product of an environment where many, many novices come, but you are somehow an "expert" because of your modestly advanced skill compared to them? It sounds to me as if you're believing your own fairy tales...


:davis:
  #7  
Old 21-Feb-2008, 07:59
davis
 
Posts: n/a

Re: I/O array problem with data files


Quote:
Originally Posted by Mr_Peepers
Thanks Davis, That really seemed to help fix reading and outputting.

No worries.

Quote:
Originally Posted by Mr_Peepers
I should have mentioned, with that data, some things need to be calculated, namely average x, y, and z values, and simple searches to find the smallest and largest numbers.

Luckily, the organization of data in the linked list works well for those kinds of algorithms...however, you're likely to find that "searches" and particularly sorting algorithms oftenly tend toward "array" data.

Quote:
Originally Posted by Mr_Peepers
So with this allocation method, average for x would go something like this?

...if we're going to traverse the list, we'd probably want to try to figure out a way to do all of our calculations in a single pass through the list. Are we averaging x, y and z or are we averaging all xes, all ys and all zs?

Quote:
Originally Posted by Mr_Peepers
CPP / C++ / C Code:
while ( p_tmp != NULL )
  {
    total += p_tmp-> x;
    count += 1;
    p_tmp = p_tmp -> next;
  }

Why use count? Didn't we already tell the user how many "chunks" we read from the input? Don't we already know how many x data points there are?

Quote:
Originally Posted by Mr_Peepers
having of course declared total and count, with average being total / count.

You are essentially correct. We must also assign p_tmp to the head node, which is (very unprotectedly) p_node. In my code, I didn't mention it, but the code should obviously be seen as "protecting" p_node as the "head" value for as long as we intend to access the list...elsewise, we are probably "in the weeds" and/or "leaking memory."

By searching, do you mean for the lowest/highest between all of x, y and z (I used x, y, f) or the lowest/highest of the xes, the lowest/highest of the ys, etc.?

I might create a separate data structure, but plain old data (POD) is fine, too.

Something else to consider is that these things are sometimes cummulative. That is, what you learn about using arrays in the "previous block" will be used in the "next block" thereby building upon code you've already written. For example, let's say that you then need to sort the "arrays" of data using a simple sorting algorithm whose arguments require integer arrays. Converting from a list to an array is not very difficult, but it may require some activities that you haven't yet been exposed to. I don't know.

Just note that if you don't reasonably well understand the code that I put forth, it may come back to haunt you if you build your solution based on it. I offer it here because it was expedient for me to do so. It was easier for me than creating a static array and then resizing the array (if needed) and then writing functions to do work on arrays.

Here you can (should) see that you can easily pass a pointer to the head pointer into a function that would calculate the average(s) for you very easily.

Another place that you can calculate the averages is AS you read the data. Why spend another cycle traversing the list when you have the data points at the point that you read them?


:davis:
  #8  
Old 21-Feb-2008, 15:29
admin's Avatar
admin admin is offline
Administrator
 
Join Date: Sep 2002
Posts: 858
admin will become famous soon enough

Re: I/O array problem with data files


davis, what is wrong with you?

So you disagree with Walt's suggestion, post your reasons why and be done with it! Your personal attack is uncalled for.
__________________
Custom BB codes you can use here:
[HTML] | [C++] | [CSS] | [JAVA] | [PY] | [VB]
  #9  
Old 21-Feb-2008, 19:22
davis
 
Posts: n/a

Re: I/O array problem with data files


Quote:
Originally Posted by admin
davis, what is wrong with you?

I'm tired of listening to wannabe "advice" from WaltP.

www.oopweb.com

Here is a direct quotation:


printf() debugging

printf debugging is our term for a debugging technique we encounter all too often. It consists of ad hoc addition of lots of printf (C) or cerr or cout (C++) statements to track the control flow and data values in the execution of a piece of code.

This technique has strong disadvantages:


It is very ad hoc. Code is temporarily added, to be removed as soon as the bug at hand is solved; for the next bug, similar code is added etc. There are better ways of adding debugging information, as you shall see shortly.

It clobbers the normal output of your program, and slows it down considerably.

Often, it does not help. Output to stdout is buffered, and the contents of the buffer are usually lost in case of a crash. Thus, you'll most likely miss the most important information, causing you to start looking in all the wrong places [2] .

If you consider using printf debugging, please check out the use of assertions (see the section called Assertions: defensive programming) and of a debugger (see the section called The debugger); these are often much more effective and time-saving.

There are some circumstances where printf debugging is appropriate. If you want to use it, here are some tips:


Produce your output on stderr. Unlike stdout, stderr is unbuffered. Thus using stderr, you're much less likely to miss the last information before a crash.

Do not use printf directly, but define a macro around it, so that you can switch your debugging code on and off easily.

Use a debugging level, to manage the amount of debugging information.


Not enough?

www.oopweb.com


3.1 Don't Use printf()/cout As Your Main Debugging Devices

As seen above, the confirmation process often involves checking the values of variables at different points in your code and different points in time. In the past, you probably did this by adding temporary printf or cout statements to your C or C++ source file. This is very inconvenient: You have to recompile your program after you add them, and you may have to add a large number of them, say if you want to check the value of some variable at several different places in your program. Then after recompiling and running the program, you realize that there are even more places at which you need printf/cout statements, so you have to recompile again! Then after you fix that bug, you have to remove all these printf/couts, and start adding them to track down the next bug. Not only is this annoying, but it is distracting, making it difficult to concentrate, i.e. you will be apt to lose your train of thought on finding the bug.

A debugging tool allows you to print out values of variables much more conveniently: You don't have to recompile, and you can ask the debugging tool to monitor any variables you like, automatically. Again, the ``convenience factor'' here is quite important. The less time you spend on recompiles, etc., the more time-and mental energy-you have available to concentrate on hunting down the bug.

Even more important, the debugging tool will tell you where in your program a disastrous error (e.g. a ``segmentation fault'') occurs. In addition, it can tell you where the function generating the seg fault was called from. This is extremely useful.

There are times when printf/couts are useful in conjunction with a debugging tool, but you'll be doing yourself a favor if you use the debugging tool, not printf/couts, as your main debugging device.


I think that YOU should decide whether or not you want to build a forum around his very limited perspective and experiences or assault those who promote alternatives that are truly beneficial to aspiring programmers.

What is wrong with saying that WaltP is fascinated with printf/cout as a debugging tool? He regularly recommends it and, if ever, rarely recommends alternatives. Why should we all jump to his perceived "aid" when he claims some kind of "attack" made by me for denouncing his "choice" of debugging tools?

This is YOUR forum. You don't need me or anything that I bring to the table in order to have WaltP remind newbies that they should read the guidelines before posting.

Let me know if you want me to further contribute to this forum. Nah, **** that. Delete me. I'm tired of this bullshit where a total ****ing wannabe named WaltP is the "hero" and I'm the villian because I call his shit out for it.


**** you.


:davis:
 
 

Recent GIDBlogInstall Adobe Flash - Without Administrator Rights by LocalTech

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Memory leak when nothing is happening... How can I even debug this ? Algar MS Visual C++ / MFC Forum 10 19-Nov-2007 07:17
[Include] Doubly-linked List dsmith C Programming Language 6 14-Apr-2006 13:12
Need help deleting the last element in the array headphone69 C++ Forum 2 15-Mar-2006 19:31
Strange C++ code memory leakage problem gaoanyu C++ Forum 7 04-Nov-2005 08:09
template comiling problems - need expert debugger! crq C++ Forum 1 01-Feb-2005 21:26

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 10:22.


vBulletin, Copyright © 2000 - 2010, Jelsoft Enterprises Ltd.