我创建了一个程序,要求用户输入5个名字,这些名字被记录在一个字符串向量中。之后程序应该抓住每个名字的第一个和最后一个字母并输出它们。我的程序编译正常,但输入名称后,我得不到程序的输出。
任何人都可以帮我纠正这个问题,以便打印输入的每个姓名的第一个和最后一个字符吗?
#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;
}
答案 0 :(得分:1)
#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;
}
答案 1 :(得分:0)
您已将其作为if语句输入。将其更改为while循环
while ( !names[n].empty() )
{
first_letter = *names[n].begin();
last_letter = *names[n].rbegin();
std::cout << first_letter << " " << last_letter << endl;
n++;
}