Reputation: 17
I have to write this program for class that takes in a C++ file, removes all the comments from the code and reads out the code to either a new file or in the output. After a long time of working on this, I keep receiving compilation errors, and I just can't figure out what I'm doing wrong. Some help would be much appreciated.
#include <iostream>
#include <fstream>
#include <string>
#include <cassert>
#include <cstdio>
using namespace std;
void remove_comments (ifstream& , ofstream&); //function declaration
int main(void)
{
int i;
string inputFileName;
string outputFileName;
string s;
ifstream fileIn;
ofstream fileOut;
char ch;
do
{
cout<<"Enter the input file name:";
cin>>inputFileName;
}
while (fileIn.fail() );
cout<<"Enter the output file name: ";
cin>>outputFileName;
fileIn.open(inputFileName.data());
assert(fileIn.is_open() );
remove_comments ( fileIn , fileOut);
fileIn.close();
fileOut.close();
return 0;
}
void remove_comments( ifstream& fileIn , ofstream& fileOut)
{
string line;
bool flag = false;
while (! fileIn.eof() )
{
getline(fileIn, line);
if (line.find("/*") < line.length() )
flag = true;
if (! flag)
{
for (int i=0; i < line.length(); i++)
{
if(i<line.length())
if ((line.at(i) == '/') && (line.at(i + 1) == '/'))
break;
else
fileOut << line[i];
}
fileOut<<endl;
}
if(flag)
{
if(line.find("*/") < line.length() )
flag = false;
}
}
The errors I get are:
In function 'void remove_comments(std::ifstream&,std::ofstream&)':
53: error: 'fileIn' was not declared in this scope
67: error: expected primary-expression before 'else'
67: error: expected `;' before 'else'
70: error: 'fileOut' was not declared in this scope
At global scope:
81: error: expected declaration before '}' token
Upvotes: 0
Views: 132
Reputation: 251
remove_comments( ifstream& , ofstream&)
you didn't write parameters names, it should be
remove_comments( ifstream& fileIn, ofstream& fileOut)
you also missed a couple of brackets at the end
Upvotes: 2
Reputation: 57688
A variable declared in main()
is not available to other functions. Similarly with all functions. This is called variable scope.
Your variable fileIn
in remove_comments
has no declaration inside the function, which is what the compiler is complaining about. Perhaps, like @Ahmed Magdy Guda said, you forgot to put parameters in your function declaration and definition.
Upvotes: 0