How would i change this to read from a file and then output to a file? File = \"
ID: 3553823 • Letter: H
Question
How would i change this to read from a file and then output to a file?
File = "functions"
and is formatted like this
1 3
2 0
4 3
0 5
10 3
#include <iostream>
#include <cstdlib>
using namespace std;
void readnums (int& b, int& e) {
int correctInput;
cout << "Enter the base and the exponent:";
cin>>b>>e;
if (!cin) {cout<<"Disaster! Terminating program."<<endl;
exit (-1);
}
correctInput=(b>=0)&&(e>=0);
while (!correctInput){
cout<<"Something wrong! Try again..."<<endl;
cout<<"Re-enter base and exponent:",
cin>>b>>e;
if(!cin){
cout<<"Disaster! Terminating program."<<endl;
exit (-1);
}
correctInput = (b>=0)&&(e>=0);
}
}
int exp (int b, int e){
int result;
result= 1;
while (e!=0){
result=result*b;
e=e-1;
}
return (result);
}
int main ()
{
int x, y;
readnums (x, y);
cout<<exp(x,y)<<endl;
return 0;
}
Explanation / Answer
#include <iostream>
#include <cstdlib>
#include<fstream>
using namespace std;
void readnums (int& b, int& e) {
ifstream myfile ;
myfile.open("functions.txt");
int correctInput;
myfile>>b>>e;
if (!cin) {cout<<"Disaster! Terminating program."<<endl;
exit (-1);
}
correctInput=(b>=0)&&(e>=0);
while (!correctInput){
cout<<"Something wrong! Try again..."<<endl;
cout<<"Re-enter base and exponent:",
myfile>>b>>e;
if(!cin){
cout<<"Disaster! Terminating program."<<endl;
exit (-1);
}
correctInput = (b>=0)&&(e>=0);
}
}
int exp (int b, int e){
int result;
result= 1;
while (e!=0){
result=result*b;
e=e-1;
}
return (result);
}
int main ()
{
int x, y;
readnums (x, y);
ofstream myfile ;
myfile.open("output.txt");
myfile<<exp(x,y)<<endl;
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.