USING C++ ONLY Purpose Learn to use heap memory and properly clean up your data
ID: 3879053 • Letter: U
Question
USING C++ ONLY
Purpose Learn to use heap memory and properly clean up your data without leaks or corruption Redirect cin and cout to file i/o Instructions Read lines of text from std:cin into a ragged cstring array until the end of line is reached Each element of the ragged array must be allocated on the heap Each line can have zero, one, or multiple names For example Doublade Drilbur Hippopotas Inkay Jigglypuff Illumise Magcargo Mespirit Mudkip Ninetales Persian Phantump Seadra Shelmet Sliggoo Solrock Spearow Spheal Staryu Tangela Tentacool Process the data stored in the ragged array to std:cout in reverse order. Mespirit Magcargo Illumise Jigglypuff Inkay Hippopotas Drilbur Doublade Mudkip Ninetales Seadra Phantump Persian Shelmet Tentacool Tangela Staryu Spheal Spearow Solrock Sliggoo A name can be a maximum of 256 characters There is no limit on the number of lines or the number of names per lineExplanation / Answer
#include <bits/stdc++.h>
using namespace std;
int main() {
string **array;
ifstream cin("input.txt"); //linking cin to file inputstream
string line;
int l = 0;
int w = 0;
while(getline(cin, line))
{
cout<<"Processing line-"<<(l+1)<<" ";
istringstream iss(line);
string word;
w = 0;
if(l==0) { //Dynamic memory allocation for line 1
array = new string*[1];
} else { //Dynamic memory allocation for subsequent lines
string **a = new string*[l+1];
copy(array, array + min(l, l+1), a);
delete[] array; //deleting unused memory
array = a;
}
while(getline(iss, word, ' ' ) ) {
if(w==0) { //Dynamic memory allocation for first word
array[l] = new string[1];
array[l][w] = word;
} else { //Dynamic memory allocation for subsequent words.
string *a = new string[w+1];
copy(array[l], array[l] + min(w, w+1), a);
delete[] array[l]; //deleing unused memory
array[l] = a;
array[l][w]= word;
}
w++;
}
cout<<"Words in line "<<(l+1)<<" ";
for(int i = 0; i<w;i++) { //loop to print stored words in heap memory.
cout<<array[l][i]<<" ";
}
cout<<" ";
l++;
}
cin.close(); //closing file
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.