Reputation: 3
Ok so here's my code. I'm getting no errors in the compiler, however when I run this program it lets me input 2 names then crashes with a Window's Error. What in the heck am I doing wrong?!
#include <iostream>
using namespace std;
//declaration of variables
int i; // Loop Counter
int x; // Number of Family Members
int main()
{
string FamilyName[x]; // Array of Names
cout << "Enter Number of Family Members" <<endl;
cin >> x;
for (i = 0 ; i < x ; i++){
cout << "Enter Family Member's Name: " <<endl;
cin >> FamilyName[i];
}
for (i = 0 ; i < x ; i++){
cout << FamilyName[i] <<endl;
}
return 0;
}
Upvotes: 0
Views: 131
Reputation: 169
You need to either allocate reasonable memory for FamilyName or use STL:
string[] FamilyName;
//after get x
FamilyName = new string[x];
or
vector<string> FamilyName;
cin << temp_string;
FamilyName.push_back(temp_string);
Upvotes: 0
Reputation: 346
The size of your array should be constant.
Maybe use a vector of strings since vectors can grow dynamically.
string name;
vector<string> FamilyName;
for(int i = 0; i < x; i++)
{
cin >> name;
FamilyName.push_back(name);
}
Either that or give your array a constant size larger than any family size you might encounter.
string FamilyName[100];
if you wouldn't ever get a family with over 100 members.
Upvotes: 0
Reputation: 3408
You can solve the problem in two ways, allocate the array to a large size(x should be initialized...and it should be a constant value) and then the code becomes:
#include <iostream>
#include <string>
using namespace std;
//declaration of variables
int i; // Loop Counter
const int x = 500; // MAX Number of Family Members
int main()
{
string FamilyName[x]; // Array of Names
int count;
cout << "Enter Number of Family Members" <<endl;
cin >> count;
for (i = 0 ; i < count ; i++){
cout << "Enter Family Member's Name: " <<endl;
cin >> FamilyName[i];
}
for (i = 0 ; i < count ; i++){
cout << FamilyName[i] <<endl;
}
return 0;
}
Or use dynamic memory allocation to read the number of family member first and then do the allocation:
int main()
{
int count;
cout << "Enter Number of Family Members" <<endl;
cin >> count;
auto FamilyName = new string[count];
for (i = 0 ; i < count ; i++){
cout << "Enter Family Member's Name: " <<endl;
cin >> FamilyName[i];
}
for (i = 0 ; i < count ; i++){
cout << FamilyName[i] <<endl;
delete[] FamilyName;
}
Hope this helps
Upvotes: 1
Reputation: 461
You are not allocating any memory to your string array, on this line string FamilyName[x]; // Array of Names
x
is not defined. It also may be a good idea to set a max array size or have some way of pushing on to the end of the array.
Upvotes: 0