I have errors with the following code and I am not sure what I am doing wrong. My compiler is microsoft visual c++ 2010. This code compiles the C++ source file through the system() function and then runs the resulting program with the given input file. The program then compares the output file generated by this program with the expected result file to determine whether or not the program is correct. My following code is:
#include <iostream>
#include <fstream>
using namespace std;
string getfile(string);
int execute(string,string);
void checkit(ifstream&,ifstream&);
int main() {
string command;
string input,output,source,expected;
ifstream in,exp;
int code;
source=getfile("source");
input=getfile("input");
expected=getfile("expected result");
code=execute(source,input);
if(code!=0) {
cout<<"Execution error,program aborted!\n";
system("pause");
return 0;
}
in.open("output.txt"); //open file
if(in.fail()) { //is it ok?
cout<<"created output file did not openplease check it\n";
system("pause");
return 1;
}
exp.open(expected.c_str()); //open file
if(exp.fail()) { //is it ok?
cout<<"expected output file did not openplease check it\n";
system("pause");
return 1;
}
checkit(in,exp);
in.close();
exp.close();
system("pause");
return 0;
}
void checkit(ifstream& act,ifstream& exp) {
int i,error=0,j;
int n,m,total=0;
act>>n;
exp>>m;
while(act&&exp) {
total++;
if(n!=m)
error++;
act>>n;
exp>>m;
}
if(act || exp)
error++;
if(error==0)
cout<<"The output of the program iscorrect.\n";
else
cout<<"The output of theprogram is not correct.\n";
cout<<"Your grade is"<<(total-error)/(double)total*100.<<"%\n";
}
int execute(string source,string input) {
string command,minusc;
int c,pos;
pos=source.find('.',0);
minusc=source.substr(0,pos);
command="gcc -o "+minusc+" "+source;
c=system(command.c_str());
if(c!=0) {
cout<<"compilation error\n";
return c;
}
command=minusc+" "+input+" > output.txt";
c=system(command.c_str());
if(c!=0)
cout<<"execution error\n";
return c;
}
string getfile(string mess) {
string file;
cout<<"Please enter the name of the "<<mess<<"file: ";
cin>>file;
return file;
}
You should say what your compiler errors were. I tried it in Visual Studio and it turns out you need
#include <string>
at the top of your file.
system
Calls the host environment's command processor with command parameter, It's has different behavior on linux and windows. Assumed all of you input is valid.
system
function, gcc usually installed as default in linux, so it runs ok. Visual C++ provides command-line tools, please refer the help page: http://msdn.microsoft.com/en-us/library/f35ctcxw.aspx for detail.
Simple to say, you can repalce ' gcc ' in your code with ' CL ' so that it can compile on windows (use VC++).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.