首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >处理输入和输出的C++函数

处理输入和输出的C++函数
EN

Stack Overflow用户
提问于 2020-06-12 14:36:38
回答 2查看 89关注 0票数 1

我被赋予了在c++中编写代码的任务,我必须开发一个算法来检查以下条件中的3个数字,如果第一个数字指数第二个数等于第三个数字,那么它应该返回真假。我使用幂函数来查找第一个数字被提升到第二个数字,而另一个称为comapare(num1,num2,num3)的.My pogramme函数工作得很好,但问题是它在控制台中显示了结果,我想要输出到我命名为outfile的输出文件中,当我这样做时,我会收到一个错误,它说没有声明outfile,我会很感激能够输出到输出文件的任何帮助。下面是我的代码

代码语言:javascript
复制
#include <iostream>
#include<fstream>

using namespace std;

double powerfunc(double num1,double num2){ // power function  

    double base=num1,exponent=num2,result;//decalsring base and exponent

    for(int i=1;i<exponent;i++){
        base=base*base;
        result=base;
    }
    return result;
}

double compare(double x, double y,double z){//Comapares if x exponent y gives z and return 
    //Return true or false

    int storersults;
    if( (powerfunc(x,y)== z)){
        cout<<"true"<<endl;
        //outfile<<"true"<<endl;
        storersults=powerfunc(x,y);
        cout<<"results is "<<storersults;
        //outfile<<"results is "<<storersults;
    }
    else{
        cout<<"false"<<endl;
        //outfile<<"false"<<endl;
        storersults=powerfunc(x,y);
        cout<< " results is "<<storersults;
        //outfile<<"results is "<<storersults;
    }
    return storersults;
}

int main(){
    ifstream infile;
    ofstream outfile;

    infile.open(" input.txt");
    outfile.open("output.txt");// I wanna link output to functions above and get results // I wann get results on outputfile not on console
    // double a,b,c;
    //infile>>a,b,c;
    powerfunc(3,2);//This functions finds power of 3 and 2
    compare(3,2,9);//This fucnions compare if 3^2=9 then retuens true

    }
    infile.close();
    outfile.close();
    return 0;
}
EN

回答 2

Stack Overflow用户

发布于 2020-06-12 14:41:21

您可以接受要执行输出的函数中的输出流,如下所示:

代码语言:javascript
复制
double compare(double x, double y,double z, std::ostream &out) {
                                          // ^^^ accept some stream
  out << "hello"; // print whatever output to the stream
}

然后在main中,您可以这样称呼它:

代码语言:javascript
复制
outfile.open("output.txt");
compare(3,2,9, std::cout);   // to print to console
compare(3,2,9, outfile);     // to print to file
票数 1
EN

Stack Overflow用户

发布于 2020-06-12 14:43:34

我得到了一个错误,它说没有声明出文件,

因为outfilemain()之外使用

你犯了语法错误。拆下那个撑子

代码语言:javascript
复制
int main(){
    ifstream infile;
    ofstream outfile;

    infile.open(" input.txt");
    outfile.open("output.txt");// I wanna link output to functions above and get results // I wann get results on outputfile not on console
    // double a,b,c;
    //infile>>a,b,c;
    powerfunc(3,2);//This functions finds power of 3 and 2
    compare(3,2,9);//This fucnions compare if 3^2=9 then retuens true

} // <- main() ends here
    infile.close();
    outfile.close();
    return 0;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62346521

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档