12

How to store (or convert) a specific column of an ASCII file into a table using...

 2 years ago
source link: https://www.codesd.com/item/how-to-store-or-convert-a-specific-column-of-an-ascii-file-into-a-table-using-c.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

How to store (or convert) a specific column of an ASCII file into a table using c ++?

advertisements

I am newbie in C++.

I got an ASCII file of 3 columns and 143 rows. First column has integer numbers while the rest of the two columns have floats.

Goal: Store individual three columns into three Arrays of size 143, each.

Problem: When print using cout, the last row is repeated, I don't know why.

ASCII file sample:

2   41.3    25
2   46.2    30
2   51.5    40
2   56.7    45
3   49.5    525
3   46.2    450
3   54.0    575
3   59.5    650
5   36.0    500
5   39.0    525
5   31.8    480
5   36.4    520

And my code:

void my_code()
 {
    FILE *pfile;
    int ball[150];
    float energy[150], channel[150];
    int ball1[150], i=0;
    float energy1[150], channel1[150];
    pfile = fopen("./ascii.txt","r");
    if (!pfile) continue;
    while(!feof(pfile))
    {
      fscanf(pfile,"%d\t%f\t%f",&ball[0],&energy[0],&channel[0]);
      ball1[i]=ball[0];
      energy1[i]=energy[0];
      channel1[i]=channel[0];
      cout<<i<<"\n";
      cout<<ball1[i]<<" "<<" "<<energy1[i]<<" "<<channel1[i]<<"\n";
      i++;
     }
 }

Please help me to understand. I am also willing to get suggestions/advices for improvement of my code.


Your trouble lies in the position of your loop test within the loop. Try this, instead:

while(true)
{
  fscanf(pfile,"%d\t%f\t%f",&ball[0],&energy[0],&channel[0]);
  if (feof(pfile)) break;
  ball1[i]=ball[0];
  energy1[i]=energy[0];
  channel1[i]=channel[0];
  cout<<i<<"\n";
  cout<<ball1[i]<<" "<<" "<<energy1[i]<<" "<<channel1[i]<<"\n";
  i++;
}

Newcomers to programming often err in this way. Your loop is actually pretty good for an early attempt, but do consider precisely the point from which a loop wants to exit. If your exit point is off, you'll get odd effects on the loop's final iteration.

Once you understand the answer, be advised that many programmers used to deprecate (and some still deprecate) the style of breaking a loop from the midst of the loop action. That is, some programmers used to tend not to like break. Personally, after three decades of programming, I usually disagree with the deprecation, but if you have a programming instructor who dislikes break, you should naturally take the instructor's preference into account.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK