如何在函数中读取文件后使用该文件,并在另一个函数中进行计算?
这是我试图制作的代码..
void readFile(ifstream&); //file reading
void DisplayAdd(ifstream& somefile); //here what i don't understand do i use void or int !
//and how is it going to use the data from the file !!
int main()
{
ifstream inputfile;
inputfile.open("numbers.txt");
readFile(inputfile); //calling function to make reading file
DisplayAdd(inputfile); //calling function to make addition
}
inputfile.close(); //closing file
return 0;
}
void readFile(ifstream& somefile) //reading data from file ..
{
double num1,num2,num3,num4,num5;
while(somefile>>num1>>num2>>num3>>num4>>num5)
cout<<num1<<endl<<num2<<endl<<num3<<endl<<num4<<endl<<num5<<endl;
}
void DisplayAdd(ifstream& somefile) //how to make the calculation here is it like this !
{cout<<num1+num2+num3+num4+num5;
}
答案 0 :(得分:0)
没有
#include <iostream>
#include <fstream> // you include HEADER needed for files using
using namespace std;
ifstream f("date.txt"); // you DECLARE the FILE data
int returnNumber(); // you PROTOTYPE your function (I guess you know about this)
int nr, a = 10, b = 10; // you declare your GLOBAL variables
int main()
{
cout << returnNumber(); // you SHOW the number you got after calculation on screen
return 0;
}
int returnNumber(){ // here's the function; int type because you return a integer value
f >> nr; // you READ the VALUE from the file
nr = nr + a + b; // you make a CALCULATION inside function
return nr; // you RETURN the number
}