I need to write a program that dynamically allocates an array of a size input by the user and fill it with std::strings. It has to then sort the array. So I want to know how to fill a dynamically allocated array of std::strings.
#include <iostream>
#include <string>
#include "keep_window_open.h"
int getSizeInput();
std::string& getStringArrayInput(std::string nameArray[], constint size);
int main()
{
usingnamespace std;
cout << "How many names do you wish to enter? ";
int size = getSizeInput();
cout << "Please enter " << size << " names (first names only): ";
string *nameArray = new string[size];
*nameArray = getStringArrayInput(nameArray, size);
keep_window_open();
return 0;
}
int getSizeInput()
{
usingnamespace std;
int size;
cin >> size;
cin.ignore(32767, '\n');
return size;
}
std::string& getStringArrayInput(std::string nameArray[], constint size)
{
usingnamespace std;
for (int count = 0; count < size; ++count)
{
cin >> nameArray[count];
cin.ignore(32767, '\n');
}
return nameArray[size];
}
For taking input for the array, is what I have fine or did I do it wrong? If it's wrong, help me fix it please. Or it would be better to just take the input for it in main() instead?
And in the meantime, I'll be reading the info in that link you provided.
You should definitely fill the array in a function like in your first code, not in main. Keep main as clean as possible.
As for the sorting part. I mean, if you want to sort numbers smallest to biggest for example that's easy. But how do you want to sort your strings? If I enter 10 names, how do you want to sort them, alphabetically?
So even though function fillArray() doesn't return anything, it still acts as though you filled the array and printed it in main()? Good to know; I'll try that. Thanks.
Edit: When I tried to fill the array in a void function, I got an empty array. The for that function right now is this:
int main()
{
usingnamespace std;
cout << "How many names do you wish to enter? ";
int size = getSizeInput();
string *nameArray = new string[size];
getStringArrayInput(size);
selectionSort(nameArray, size);
displayArray(nameArray, size);
keep_window_open();
return 0;
}
Edit2: I got it. Passing the array into the function worked.
Edit3: I just remembered to delete the array and set to point to nullptr, so I just typed that in rebuilt it.