c++ The objective of this close lab is to use as little memory as possible, by u
ID: 3779768 • Letter: C
Question
c++
The objective of this close lab is to use as little memory as possible, by using pointers, allocation, and deallocation in order to reuse the same memory locations.
Assignment: Write a program to read in the text file clab12.txt and process it as follows. (See the data file clab12.txt, and a sample run from a different data file sample.txt and sampleout.txt.)
Each line of clab12.txt contains:
a character which represents a data type:
's' for string
'i' for integer
'd' for double
'q' for quit
any other character is illegal
a data item of the given type
Declare pointers to the three data types, and variables to hold the sum of integers, the sum of the doubles, and the concatenation of the strings.
As you read each line of the file do the following. If the data type character is illegal, output an error message. Otherwise proceed as follows. Allocate a memory location to hold the appropriate data type, and read the data into that location. (To save space, do not declare another variable to hold the data.) Output the data read and the address of the data. Add the data to the
Explanation / Answer
#include <cstdlib>
#include <iostream>
#include<fstream>
using namespace std;
int main(int argc, char *argv[])
{
ifstream in("clab12.txt");
char c;
int *p1;
double *p2;
string *p3;
int sum1;
double sum2;
string s3;
in>>c;
while(c!='q')
if(c=='i')
{
p1=new int;
in>>*p1;
cout<<*p1<<" "<<p1<<endl;
sum1=sum1+*p1;
delete(p1);
}
else if(c=='d')
{
p2=new double;
in>>*p2;
cout<<*p2<<" "<<p2<<endl;
sum2=sum2+*p2;
delete(p2);
}
else if(c=='s')
{
p3=new string;
in>>*p3;
cout<<*p3<<" "<<p3<<endl;
s3=s3+*p3+" ";
delete(p3);
}
else
cout<<"Data type incorrect"<<endl;
in>>c;
}
cout<<"-----Sum-----Address"<<endl;
cout<<sum1<<" "<<&sum1<<endl;
cout<<sum2<<" "<<&sum2<<endl;
cout<<s3<<" "<<&s3<<endl;
system("PAUSE");
return EXIT_SUCCESS;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.