Solved

how to skip lines in C++ when reading from a file?

Posted on 2002-03-21
14
491 Views
Last Modified: 2012-08-13
I have a data file which looks like:

#&comments lines ....
#&

1.3245 5.2341
2.3344 6.1123

#& some other comments ....

2.3001 4.5003

How to write a function to read the pairs of x and y data but skip all the comments lines? Using C++.
0
Comment
Question by:oatnusigma
  • 4
  • 3
  • 2
  • +4
14 Comments
 
LVL 86

Accepted Solution

by:
jkr earned 100 total points
Comment Utility
#include <iostream>

// ...

istream str ( "myfile.txt", ios::nocreate);
char buf [ MAX_LENGTH];

 while ( !str.eof()) {

   str.getline ( buf, sizeof ( buf));

   // skip comment lines
   if ( !strncmp ( buf, "#&", 2)) continue;

   // process line
 }

 str.close();


0
 

Expert Comment

by:lazypinkmonkey
Comment Utility
istreaf FILE("file.txt", ios::open);
char BUF[120];

FILE.getline(BUF, 120);

while(FILE)
{
  if( !isdigit(BUF[0] )   // returns true if a digit
  {                       // if not a digit, get next line
     FILE.getline(BUF, 120);
  }

  else                    // otherwise it is a digit and
  {                       // do whatever
.
.
.
  }
0
 
LVL 86

Expert Comment

by:jkr
Comment Utility
May I ask what makes your proposal soooo unique (and different from my comment) that you just *had* to post it as an answer?

BTW, what's 'istreaf'? Can't find that class anywhere...
0
 

Expert Comment

by:lazypinkmonkey
Comment Utility
Sorry to step on your vast expertise toes. Your comment wasn't accepted as the answer so I tried for a different approach.

Never ever made a typo in your life, eh? Well gosh golly gee, I've just found Mr. Perfect!
0
 
LVL 86

Expert Comment

by:jkr
Comment Utility
>>Never ever made a typo in your life, eh? Well gosh golly gee, I've just found Mr. Perfect!

No, but if you want to post an "Answer", and there is already a similar comment, you'd better make sure that there are none of them :o)
0
 
LVL 49

Expert Comment

by:DanRollins
Comment Utility
hi lazypinkmonkey,
The experts in this section have agreed to post comments rather than answers.  This is mainly to benefit the question askers since it provides more, and more varied input for them.  That convention provides the added benefit that, when followed, one expert won't ever lock a question with an answer that is substantially similar to a previously-posted comment.

So, in the future, please post comments, like everyone else.  Thanks!

-- Dan

0
 
LVL 4

Expert Comment

by:AssafLavie
Comment Utility
Another suggestion:

ifstream f("thefile");
while (f)
{
     double x, y;
     if (!(f >> x))
     {
          f.clear();
          f.ignore(numeric_limits<int>::max(), '\n');
     }
     else
     {
          f >> y;
          // ... use x, y ...
     }    
}

or, if you feeling particularly jaunty:
ifstream f("thefile");
while (f)
{
     double x, y;
     if (!(f >> x >> y))
     {
          f.clear();
          f.ignore(numeric_limits<int>::max(), '\n');
          continue;
     }
     // ... use x, y ...
}

0
Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

 

Expert Comment

by:campione
Comment Utility
Its very easy to code this one, but you'll have to follow a pattern for all your programming problems. I recommend solving each problem in a logical way.

In this case

PROBLEM
-------
1. Take Input from File (not a big deal)
2. Neglect remarks (big deal lol no damn easy)
3. Take necessary input using inbuilt features of c++ which actually help out task (you'll see how)


STEPS
-----
1. I agree with most of you all on this one, just include iostream and declare ifstream object like this

ifstream("filename.txt");


2. well now our file is ready for input, so you need to neglect the remarks. My logic on this one is to take input from the file line by line and if the first two characters are '#&' then just continue loop and take no input. code for this would be

if(strncmp(line, "#$", 2)==0)
continue;
else { take input }

the strncmp function here compares the first two characters in the variable line with "#$" and if found returns 0 else returns non zero.


3. congrats you have solved almost 66.67% approx of your problem. Now our next speed breaker comes when you have to take the xy inputs
thats easy, in the else code u see above in step 2 do this

if(strncmp(line, "#$", 2)==0)
continue;
else { cin>>x>>y; } // assuming x and y are of float type.


now I'll do what others do, give a code for your problem

code snippet here
//////////////////////////////////////////////

float x[10], y[10]; // you can change this 10 hehe
ifstream DATA("filename.txt");
char buffer[100];


while(FILE) // or while(!FILE.eof())
{
  DATA.getline(buffer,100);

  if(strcmp(buffer, "#$", 2)==0)
    continue; // do nothing
  else
  {
    cin>>x[i]>>y[i];
    i++;
  }
}
//////////////////////////////////////////////

well you are done boy, but really this was a googly..

thats all folks!
0
 

Expert Comment

by:campione
Comment Utility
aaaaww correction

////////////////////////////////////////////////////////

STEPS
-----
1. I agree with most of you all on this one, just include iostream and declare ifstream object like
this

--------> ifstream("filename.txt"); <----------

//////////////////////////////////////////////////////

thats pointed line should be ifstream DATA("filename.txt")
or any other appropriate identifier.
0
 
LVL 49

Expert Comment

by:DanRollins
Comment Utility
You might also want to discard blank lines.

And campione's line:
      if(strcmp(buffer, "#$", 2)==0)
needs a little work.  The proper function is strncmp (with an n).  Thus...
      if( (! *buffer) || strncmp(buffer, "#$", 2)==0 ) {
            continue;
      }

-- Dan
0
 

Expert Comment

by:campione
Comment Utility
thanks Dan
0
 

Expert Comment

by:campione
Comment Utility
thanks Dan
0
 
LVL 11

Expert Comment

by:griessh
Comment Utility
Dear oatnusigma

I think you forgot this question. I will ask Community Support to close it unless you finalize it within 7 days. You can always request to keep this question open. But remember, experts can only help you if you provide feedback to their questions.
Unless there is objection or further activity,  I will suggest to accept

     "jkr"

comment(s) as an answer.

If you think your question was not answered at all, you can post a request in Community support (please include this link) to refund your points. The link to the Community Support area is: http://www.experts-exchange.com/commspt/

PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!
======
Werner
0
 
LVL 6

Expert Comment

by:Mindphaser
Comment Utility
Force accepted

** Mindphaser - Community Support Moderator **
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

What is C++ STL?: STL stands for Standard Template Library and is a part of standard C++ libraries. It contains many useful data structures (containers) and algorithms, which can spare you a lot of the time. Today we will look at the STL Vector. …
  Included as part of the C++ Standard Template Library (STL) is a collection of generic containers. Each of these containers serves a different purpose and has different pros and cons. It is often difficult to decide which container to use and …
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now