Filling array from a file with comments

Jan 28, 2013 at 11:18pm
Hi, I'm attempting to fill my array of integers from a file but can't figure out how to make it work if there are comments.

Example data file:

1
2
3
4
3 //comments here
4
5
6


It works perfectly fine without the comments. I know it needs to come after taking in the first integer. Thanks for any help.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

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


const int temp = 0;
int items[temp];

int readInput (ifstream &infile, int items[temp]);
int main()
{   ifstream infile;
    int numItems;
    infile.open("numbers.dat");

    numItems = readInput(infile, items);
    cout << numItems<<endl;
    for(int i = 0; i < numItems; i++)
       cout<< items[i]<<" ";
    cout<<endl;
    return 0;
}

int readInput (ifstream &infile, int items[temp])
{
     int max;
     while(!infile.eof())
     { infile>>max;
       for (int i = 0; i < max; i++)
        infile>>items[i];
     }
     return max;
}
Last edited on Jan 28, 2013 at 11:19pm
Jan 29, 2013 at 2:03am
You have to manually parse the line looking for comments and then strip them. There is no concept of "comments" built in to loading data from a file.
Jan 29, 2013 at 3:21am
Yea, just look for the '/' char and then look for a proceeding '/' or '*' and you know you have found the start of a comment.

1
2
3
4
5
6
char buff;
fileIn >> buff;
if (buff == '/')
    fileIn >> buff;
    if (buff == '/' or buff == '*')
         // start your comment parsing algorithm    
Jan 29, 2013 at 4:35am
It's actually more complicated than that if you want to behave exactly like a compiler. What if the 'comments' are inside a double quote string literal ? You shouldn't skip that.
Jan 29, 2013 at 4:52am
What, something like this?
 
	""/*int foo = 0;*/""""""""""""" 


I guess he would have to play around and come up with all the different combinations first. There can't be that many and simple loops could account for them once all patterns are discovered.

At least now TS is pointed in the right direction.

Last edited on Jan 29, 2013 at 4:57am
Jan 29, 2013 at 6:58am
What about using std::getline to read in an entire line to a std::string, then use the find and erase functions to ignore the comments?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
std::string line;
std::getline(fileIn, line);

unsigned pos = line.find("//");
if (pos != std::string::npos)
    line.erase(pos, std::string::npos); // erase to the end of the line

pos = line.find("/*");
if (pos != std::string::npos)
{
    unsigned end = line.find("*/");
    if (end != std::string::npos) end += 2; // size of "*/"
    line.erase(pos, end - pos); // if it wasn't found, it will erase the whole line
}
Last edited on Jan 29, 2013 at 6:59am
Topic archived. No new replies allowed.