Tuesday, July 28, 2009

C++ question about int main(int argc,char *argv[])?

I am trying to change this main function to …int main(int argc,char *argv[])…


I tried to do it below, can some one help me if it’s right?


Please help me out here!!!


**************************************...


Without using int main(int argc,char *argv[])





int main()


{


ifstream in;


ofstream out;


char buf[100];


Steel steel;





cout%26lt;%26lt;"Enter input file name: ";


cin.getline(buf, 100, '\n');


in.open(buf);


cout%26lt;%26lt;"Enter output file name: ";


cin.getline(buf, 100, '\n');


out.open(buf);


if(in)


{


while(!in.eof())


{


try


{


in.getline(buf, 100, '\n');


steel.SetExpression(string(buf));


parser.PrintAssembly(out);


out %26lt;%26lt; endl;


}


catch(IncorrectExpressionException)


{


out %26lt;%26lt; buf %26lt;%26lt;" - Incorrect Expression"%26lt;%26lt;endl%26lt;%26lt;endl;


}


}


in.close();


out.close();


}


else


{


cerr %26lt;%26lt;"Failed to open file"%26lt;%26lt;endl;


}


return 0;


}





**************************************...


And changing it to int main(int argc,char *argv[])


Is this right?





int main(int argc,char *argv[])


{


ifstream fin;


// read some data from the file


if (argc == 2)


{


fin.open(argv[1]);


}


else


{


char filename[80];


cout %26lt;%26lt; "Enter input file name: ";


cin %26gt;%26gt; filename;


fin.open(filename);


}


return 0;


}

C++ question about int main(int argc,char *argv[])?
That looks correct assuming you're trying to pass the input file into the program. So you'd run it as:





myprog in.txt





argv would be 2


argv[0] would be "myprog"


argv[1] would be "in.txt"


No comments:

Post a Comment