Interpretation of the error

When i was running my code, there always occur error.

error: invalid operands to binary expression (‘std::ifstream’ (aka ‘basic_ifstream’) and ‘long’)
if(fp == NULL)
~~ ^ ~~~~

This error doesn’t occur when using g++ compiling. (But there are another error. because ‘form’ function is root only have.)

here is my code.

    int n[20]= {4,7,10,13,16,19,21,24,27,30,33,36,39,42,45,48,51,54,57,60};
	std::ifstream fp;
	std::ofstream fo;
	for(int i=0; i<sizeof(n); i++)
	{
		fp.open(Form("test_%d.txt",n[i]));

		char line[200];
		if(fp == NULL)
		{
			cout << "No file" << endl;
			return 0;
		}
		if(fp.is_open())
		{
			ofstream fout(Form("out_test_%d.txt",n[i]));
			while (fp.getline(line, sizeof(line)))
			{
				if(line[4] == '2' && line[6] == '4')
				{
					fout<<line<<"\n";
					//cout << line << endl; This line is for the checking that this function doing well.
				}
			}
			fout.close();
		}
		fp.close();
	}

I would appreciate your advice on my results.
Thank you for reading.

First: please use “nullptr” instead of NULL. NULL is just a macro and means 0. Thus the error message claims it is comparing to long because it is interpreting NULL as number.

However, an object cannot be nullptr, only pointers can be nullptr!

Things to fix:

  • prefer std::string for reading (dont need to worry about line numbers)
  • you can loop directly over your list of numbers (always prefer the foreach loop with for( : ) instead of for( ; ; ))
  • open stream in constructor and keep scope minimal
  • at the end, you can check if you’ve read to eof. If not, an error has occurred while reading

Suggestion to rewrite (untested):

int allN[] = {4, 7, 10, 13, 16, 19, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60};
for (int n : allN) {
    std::ifstream fp(Form("test_%d.txt", n));
    if (fp.is_open()) {
        std::ofstream fout(Form("out_test_%d.txt", n));
        if (!fout.is_open()) std::cerr << "Cannot open fout\n";
        std::string line;
        while (std::getline(fp, line)) {
            if (line[4] == '2' && line[6] == '4') {
                fout << line << "\n";
                // cout << line << endl; This line is for the checking that this function doing well.
            }
        }
        // optionally add error checking, is fp at eof? is fout good?
        fout.close(); if (! fout) std::cerr << "Error wrtinng\n";
        if (!fp.eof()) std::cerr << "Error reading\n";
    }
}
2 Likes

Dear behrenhoff,

Thank you very much! Error is solved!
I think, Your code is very simple and powerful then my code. It was really helpful for me.

Thank you again!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.