I'm not sure if I used the new operator correctly here

This is a sequel to a previous thread (http://www.cplusplus.com/forum/beginner/205575/) which involved using getline() with cin.ignore () to store an arbitrary amount of number and its correspondng string, afterwhich its the data stored data is displayed.

Thanks to @
Chervil
, the problem of input has been solved by placing an intervening cin.ignore() inbetween a preceding cin object and a trailing getline(). (See http://www.cplusplus.com/forum/beginner/205575/).

Below is the program resulting from the corrections of that forum thread which I will like to subject your scrutiny and suggestions and contributions

Thanks in advance.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include<iostream>
#include<iomanip>
#include<string>

using std::cout;
using std::endl;
using std::cin;

using std::string;
using std::getline;

//Function prototypes
bool getData(double& rNum, string& Str);
//void setData(double& pNum, string& pStr);
void showData(const double pNum[], const string pStr[], const int size);

int main()
{
	//Data
	double number;
	string buffer;

	//Data Stores
	size_t arraySize{ 1 };

	double* pNumber{ new double[arraySize] };
	string* pString{ new string[arraySize] };

	double* nTemp{};													//Temporarily hold number
	string* sTemp{};													//Temporarily hold string

	size_t index{};												

	for (;;)
	{
		//Call input function
		if (!getData(number, buffer))
			break;
		//Store each data input
		pNumber[index] = number;
		pString[index] = buffer;
		index++;
		if (index == arraySize)
		{
			arraySize++;												//i.e. increase the array size
			nTemp = new double[arraySize];								//A fresh array is declared with a
			sTemp = new string[arraySize];															//corresponding increase in array dimension

			for (size_t i{}; i < index; ++i)
			{
				*(nTemp + i) = *(pNumber + i);							//Copies existing and new entries
				*(sTemp + i) = *(pString + i);
			}
			delete[] pNumber;											//frees up memory storage
			delete[] pString;

			//Reburse data
			pNumber = nTemp;
			pString = sTemp;

			nTemp = nullptr;
			sTemp = nullptr;

		}
	}
	cout << "\nData stored in arrays:\n";
	showData(pNumber, pString, index);
}
//Function to get, pass and store data
bool getData(double& rNum, string& rStr)
{
	cout << "Enter a number, or 0 to end: ";
	cin >> rNum;
	cin.ignore(1000, '\n');											//discard Newline from cin buffer

	if (rNum != 0)
	{
		cout << "Type a string (or press only Enter to exit): "
			<< endl;
		getline(cin, rStr);
	}
	return((rNum != 0) && (rStr != ""));
}
//Function to display data stored
void showData(const double aNum[], const string aStr[], const int size)
{
	for (int i{}; i < size; i++)
		cout << std::setw(8) << aNum[i] << "  " << aStr[i] << '\n';
}
Last edited on
The program appears correct.

More as a matter of preference than anything, I'd move lines 29 and 30 inside the body of the loop.
29
30
    double* nTemp{};
    string* sTemp{};	

The reason being, these are temporary variables which have no purpose either before or after that loop, hence should not be cluttering up the main().
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
    while (getData(number, buffer))
    {
        // Store each data input
        pNumber[index] = number;
        pString[index] = buffer;

        index++;

        if (index == arraySize)
        {
            arraySize++;                                    // i.e. increase the array size
            double* nTemp = new double[arraySize];          // A fresh array is declared with a
            string* sTemp = new string[arraySize];          // corresponding increase in array dimension

            for (size_t i{}; i < index; ++i)
            {
                *(nTemp + i) = *(pNumber + i);              // Copies existing and new entries
                *(sTemp + i) = *(pString + i);
            }
            delete[] pNumber;                               // frees up memory storage
            delete[] pString;

            // Reburse data
            pNumber = nTemp;
            pString = sTemp;
        }
    }


At the end of main() (line 68) there should be a pair of delete [] statements to release the allocated memory. Though it doesn't cause a problem here (the program is ending in any case), remembering to do so is a good practice, so you remember to do so in other circumstances where it may be more important.


Having got this far, you are in effect replicating the functionality of the std::vector. Depending on what your goals are, you might consider modifying the code to use vectors instead of multiple new/delete.

You could also consider using a struct or class to keep the string and double together in a single object, again depending on what are your goals.
Last edited on
@Chervil
Thanks once again for your invaluable suggestions. I really appreciate it. I was thinking, could I create a set() function where I separate the code meant to store the data into the array by calling the set() function?

Also, if I do place the variable inside the for loop, doesnt it mean that for each loop there will have to b a new declaration of the temporary variables:

1
2
double* nTemp{};
string* sTemp{};
.

Thirdly, the lines:
1
2
3
4
5
			for (size_t i{}; i < index; ++i)
			{
				*(nTemp + i) = *(pNumber + i);				//Copies existing and new entries
				*(sTemp + i) = *(pString + i);
			}

to be candid it appears as though for each entry of a pair of number and string, a fresh copying (assignment) is made replacing the last pair of data from a previous storage. Is this the case? If so, how could I modify the code structure to be more functional?

Finally, how do u reference code and show their corresponding line numbers? If you would observe, my reference above is incorrect, and I am yet to figure how it should be done.

Thanks
Last edited on
@Chervil
Thanks once again for your invaluable suggestions. I really appreciate it. I was thinking, could I create a set() function where I separate the code meant to store the data into the array by calling the set() function?

Also, if I do place the variable inside the for loop, doesnt it mean that for each loop there will have to b a new declaration of the temporary variables:

1
2
double* nTemp{};
string* sTemp{};
.

Thirdly, the lines:
48
49
50
51
52
for (size_t i{}; i < index; ++i)
{
*(nTemp + i) = *(pNumber + i); //Copies existing and new entries
*(sTemp + i) = *(pString + i);
}

to be candid it appears as though for each entry of a pair of number and string, a fresh copying (assignment) is made replacing the last pair of data from a previous storage. Is this the case? If so, how could I modify the code structure to be more functional?

Finally, how do u reference code and show their corresponding line numbers? If you would observe, my reference above is incorrect, and I am yet to figure how it should be done.

Thanks
Also, if I do place the variable inside the for loop, doesnt it mean that for each loop there will have to b a new declaration of the temporary variables:

Yes, that's what I did in the example I posted:
45
46
            double* nTemp = new double[arraySize];          // A fresh array is declared with a
            string* sTemp = new string[arraySize];          // corresponding increase in array dimension 


Thirdly, the lines:
1
2
3
4
5
    for (size_t i{}; i < index; ++i)
    {
    *(nTemp + i) = *(pNumber + i);
    *(sTemp + i) = *(pString + i);
    }
to be candid it appears as though for each entry of a pair of number and string, a fresh copying (assignment) is made replacing the last pair of data from a previous storage. Is this the case? If so, how could I modify the code structure to be more functional?

After the each cin entry, the array size is increased by 1, and all of the existing values are copied to the new array.

That means after entering say 100 values, the whole of those 100 strings and numbers have to be copied to the new array, just to make room for 1 more value. This becomes increasingly inefficient, most of the processing time will be spent doing lots of copying each time.

One way to make this more efficient is to increase the array size in larger steps. For example, you could allocate say 4 elements at the start. That means no reallocation/copying is required until after the 4th entry. Then you could increase the array size to 8, and copy the four existing values. That leaves room for 4 more. When those four are filled, increase the size to 16 and copy the existing 8. That leaves room for another eight. Or choose whatever algorithm you like, this will reduce the amount of copying considerably, since it doesn't need to be done each time, but only after entering a reasonable number of values.


Finally, how do u reference code and show their corresponding line numbers?

See the use of firstline in this article:
http://www.cplusplus.com/articles/z13hAqkS/
Last edited on
thanks boss!
I'll get back to you after effecting the corrections. I also hope to re-write the code using classes and submit a first draft. Thanks
Topic archived. No new replies allowed.