#include <cmath> #include <iostream> using namespace std; int main(int argc, cha
ID: 3623696 • Letter: #
Question
#include <cmath>#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
int n = 1234;
int d1 = n % 10; n = n / 10;
int d2 = n % 10; n = n / 10;
int d3 = n % 10;
int d4 = n / 10;
cout << d1 << d2 << d3 << d4;
int n2 = d1 + d2 + d3 + d4;
cout << n;
cout << n2;
cout << n + n2;
cout << endl;
return 0;
}
Modify the program to:
1. read the number from a file
2. compute the last four digits of the number
3. compute the reversed number of the last four digits of the number
Suppose the number is 123456789
The last four digits are 9,8,7,6 and the reversed number of the last four digits is 9876
4. add the reversed number to the original number
5. write the original number, the last four digits, the reversed number and the sum of the original number and the reversed number to a file
This is the task...
and this is what I have it so far but it says I cannot open file....how can I fix it
#include <cmath>
#include <iostream>
#include <stdio.h>
using namespace std;
int main(int argc, char* argv[])
{
char fileName[100];
cout << "Enter the file name : ";
cin >> fileName;
FILE * fp = fopen(fileName, "r");
if(fp == NULL)
{
cout << "Cannot open file."<<endl;
return 0;
}
char ch;
ch = fgetc(fp);
long num = 0;
while(isdigit(ch))
{
num = num*10 + (ch - '0');
ch = fgetc(fp);
}
long lastFour = num % 10000;
long reverse = 0;
long l = lastFour;
int digit;
while(l > 0)
{
digit = l%10;
l = l/10;
reverse = reverse *10+ digit;
}
long added = num + reverse;
FILE * fout = fopen("output.txt", "w");
fprintf(fout, "Original Number : %ld Last Four Digits : %ld Reversed Number : %ld Sum of the original and reversed number : %ld", num, lastFour, reverse, added);
return 0;
Explanation / Answer
please rate - thanks
#include <cmath>
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char* argv[])
{ifstream in;
ofstream out;
int orig,sum,n;
char filename[20];
cout<<"Enter input file name: ";
cin>>filename;
in.open(filename);
if(in.fail())
{ cout<<"input file did not open please check it ";
system("pause");
return 1;
}
cout<<"Enter output file name: ";
cin>>filename;
out.open(filename);
in>>n;
orig=n;
int d1 = n % 10; n = n / 10;
int d2 = n % 10; n = n / 10;
int d3 = n % 10; n = n / 10;
int d4 = n % 10;
int n2 = d1*1000 + d2*100 + d3 *10+ d4;
sum=orig+n2;
out<<"Original number: "<<orig<<endl;
out <<"The last four digits of original number: "<< d1 << " "<<d2 <<" "<< d3 <<" "<< d4<<endl;
out <<"the reversed number of the last four digits of the number: "<<n2<<endl;
out<<"sum of the original number and the reversed number: "<<sum<<endl;
in.close();
out.close();
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.