The binary file contains 12345678. I need help writing this in C++...This is all
ID: 3723526 • Letter: T
Question
The binary file contains 12345678. I need help writing this in C++...This is all programmed from Linux.
Write a C program that reads and interprets the attached BINARY file. Your main program must do this: 1. Run using the commandline "myprog.exe " Open argv1] as a binary file Use a while loop to loop over the file, exiting when the data is exhausted, each iteration of the . Calls a function with the name read..data that reads either a character, a short int, or a float. It . Break when you hit end of file while loop reads one element from the file. takes the type as an argument and returns a logical value of true or false depending on whether you hit end of file. Close the file Print out the following: o The number of elements read was 27 o The sum of these elements is 99Explanation / Answer
Hi.. I have written c++ program for the above.
Main.cpp
#include <iostream> // std::cin, std::cout
#include <fstream> // std::ifstream
using namespace std;
bool read_data(char c){
if(isalpha(c)){
return true;
}else if(isdigit(c)){
return true;
}else if(c==''){
return false;
}
return true;
}
int main (int argc, char *argv[]) {
ifstream is(argv[1]); // open file
char tot[100];
int a1 = 0;
char c;
while (is.get(c)){ // loop getting single characters
bool a = read_data(c);
if(!a){
break;
}else{
tot[a1]=c;
a1++;
}
}
int numelements=0;
int sum = 0;
for(int i=0;i<a1;i++){
numelements++;
int b = tot[i]-'0';
sum+=b;
//cout<< sum;
}
cout << "The number of elements read was "<<numelements<<" ";
cout << "The sum of these elements is "<<sum;
is.close(); // close file
return 0;
}
./Main.cpp input.txt
input.txt
123456789
Output:
The number of elements read was 9
The sum of these elements is 45
Please test the code and let me know any issues. Thank you. All the best.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.