I've been working on a program recently that takes names as inputs and will eventually sort & binary search them. However upon attempting to make the array a dynamic size (that would increase by one with each loop iteration), it ran into various issues.
I can make the string array composed of 20 elements and the program works, but the extra credit for my assignment is to make it a dynamic size. Currently the program crashes without any sort of error code once it reaches "getline(cin, Names[x]);". I've been searching around and I know it'd be easier to do a vector instead of an array in this case, however I don't believe I'm allowed to use vectors on this assignment.
Thanks
Original Code
using namespace std;
#include <iostream>
#include <string>
void main()
{
int x = 0;
string * Names = new string[x];
bool NameInputEnd(0);
cout << " Enter your names to be sorted\n";
cout << "To exit just press [Enter] at any time\n";
do
{
cout << x << endl;
cout << "\n< Name " << (x + 1) << " > = ";
!!**CRASHES HERE**!!
getline(cin, Names[x]);
if (Names[x].empty() || x == 19)
{
cout << "\nFinal Name Amount = " << (x + 1) << endl << endl;
NameInputEnd = 1;
continue;
}
x++;
} while (NameInputEnd == 0);
delete [] Names;
}
Changes
int tempsize(1), x(0);
string * Names = new string[tempsize];
...
do
{
...
x++;
tempsize++;
}while (NameInputEnd == 0);
An array cannot be resized once it has been created. You have to destroy it and create a new array with a copy of the existing data. For example:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
void main()
{
int x = 0;
int capacity = 20;
string * Names = new string[capacity];
string Name;
cout << " Enter your names to be sorted\n";
cout << "To exit just press [Enter] at any time\n";
do
{
cout << x << endl;
cout << "\n< Name " << (x + 1) << " > = ";
if ((!getline(cin, Name)) || Name.empty())
break;
if (x == capacity)
{
int newCapacity = capacity + 20;
string *newNames = new string[newCapacity];
copy(Names, Names + x, newNames);
delete [] Names;
Names = newNames;
capacity = newCapacity;
}
Names[x] = Name;
++x;
}
while (true);
cout << "\nFinal Name Amount = " << x << endl << endl;
delete [] Names;
}
You really should use a std::vector
, though:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void main()
{
vector<string> Names;
string Name;
Names.reserve(20); // optional
cout << " Enter your names to be sorted\n";
cout << "To exit just press [Enter] at any time\n";
do
{
cout << Names.size() << endl;
cout << "\n< Name " << (Names.size() + 1) << " > = ";
if ((!getline(cin, Name)) || Name.empty())
break;
Names.push_back(Name);
}
while (true);
cout << "\nFinal Name Amount = " << Names.size() << endl << endl;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.