繁体   English   中英

我的以下代码有错误

[英]I have errors with the following code

我的以下代码有错误,我不确定自己在做什么错。 我的编译器是Microsoft Visual C ++2010。此代码通过system()函数编译C ++源文件,然后使用给定的输入文件运行结果程序。 然后,程序将由该程序生成的输出文件与预期结果文件进行比较,以确定该程序是否正确。 我的以下代码是:

#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;
}

您应该说什么是编译器错误。 我在Visual Studio中尝试过,事实证明您需要

#include <string>

在文件的顶部。

system使用命令参数调用主机环境的命令处理器,在Linux和Windows上具有不同的行为。 假设您输入的所有内容均有效。

  • 在Linux上,当您运行程序时,它将通过system功能调用“ gcc”命令,因为gcc通常在Linux中默认安装,因此可以正常运行。
  • 在Windows上运行程序时,它还会通过命令工具调用'gcc'命令,因此您会遇到以下问题:'gcc无法识别为内部或外部命令...因为您未安装gcc在您的窗户上。

Visual C ++提供了命令行工具,请参考帮助页面: http//msdn.microsoft.com/en-us/library/f35ctcxw.aspx

简单地说,您可以在代码中用“ CL ”代替“ gcc ”,以便它可以在Windows上编译(使用VC ++)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM