NinjaZ
NinjaZ

Reputation: 25

Program for a Vector of Strings

I created a program that asks the user to enter 5 names which is recorded into a vector of strings. Afterwards the program is supposed to grab the first and last letters of each name and output them. My program compiles fine however after entering the names I get no output from the program.

Can anyone help me correct this issue so that it prints the first and last characters of each name entered?

#include <iostream>
#include <algorithm>
#include <vector>
#include <string>

using namespace std;

int main() 
{
 vector<string> names;
 char first_letter;
 char last_letter;
 string name;
 int n = 0;

 for (int i =0; i < 5; i++)
 {
  cout << " Please enter a name: ";
  cin >> name;
  names.push_back(name);
 }

 if ( !names[n].empty() )
 {
  first_letter = *names[n].begin();
  last_letter = *names[n].rbegin();
  cout << first_letter << " " << last_letter << endl;
  n++;
 }

 return 0;
}

Upvotes: 0

Views: 53

Answers (2)

Nihar
Nihar

Reputation: 355

#include <iostream>
#include <algorithm>
#include <vector>
#include <string>

using namespace std;

int main() 
{
 vector<string> names;
 char first_letter;
 char last_letter;
 string name;
 int n = 0;

 for (int i =0; i < 5; i++)
 {
  cout << " Please enter a name: ";
  cin >> name;
  names.push_back(name);
 }

 vector<string>::iterator itr = names.begin();
 for(;itr!=names.end();itr++)
{

  first_letter = *itr[n].begin();
  last_letter = *itr[n].rbegin();
  cout << first_letter << " " << last_letter << endl;


}
 return 0;
}

Upvotes: 1

user3393004
user3393004

Reputation: 1

You have entered it as a if statement. Change it to a while loop

while ( !names[n].empty() )
 {
  first_letter = *names[n].begin();
  last_letter = *names[n].rbegin();
  std::cout << first_letter << " " << last_letter << endl;
  n++;
 }

Upvotes: 0

Related Questions