0

just wondering if anyone could help me with this problem I have, the program always crashes for some reason and I'm not sure why. I'm still new to C++ so, yeah.

What it's supposed to do:

  1. Create an array of strings with 5 possible elements.
  2. Get 5 names from the user (first name and last name)
  3. Print the first and last elements of the array of strings
  4. Create a string and have user assign a sentence to the string.
  5. Print the string from (4)

Steps 4,5 were easy but I really don't get how to display the last element of the string in step 3.

int x;
string n1,n2,n3,n4,n5,user;
string array[5]={n1,n2,n3,n4,n5};

cout<<"Enter 5 names: "<<endl;

getline(cin,n1);
getline(cin,n2);
getline(cin,n3);
getline(cin,n4);
getline(cin,n5);

cout<<endl;

for(x=0;x<5;x++)
{
    int y=array[x].length();
    cout<<array[x].substr(0,1)<<"\t"<<array[x].substr(y,1)<<endl;
}

cout<<endl;
cout<<"Enter sentence for string: "<<endl;
getline(cin,user);
cout<<user<<endl;

system("pause");
return 0;
ThinkingStiff
  • 64,767
  • 30
  • 146
  • 239
NopeAvi
  • 1
  • 1

1 Answers1

1

Unlike say java the following creates 5 distinct copies of std::string. So assigning to n1 will not effect array[0]

 string n1,n2,n3,n4,n5,user;
 string array[5]={n1,n2,n3,n4,n5};

The "correct" way to do what you are after is something like

std::vector<std::string> array(5);

std::cout << "Enter 5 names: " << std::endl;

for(std::size_t x=0;x<array.size();x++) {
    std::getline(std::cin, array[i]);
} 

I have swapped out the raw array for a vector, which should be preferred over an array in almost all cases.

http://en.cppreference.com/w/cpp/container/vector

111111
  • 15,686
  • 6
  • 47
  • 62