我创建了一个程序,要求用户输入 5 个名称,这些名称被记录到一个字符串 vector 中。之后程序应该获取每个名字的第一个和最后一个字母并输出它们。我的程序编译得很好,但是在输入名称后,我没有从程序中得到任何输出。
任何人都可以帮我解决这个问题,以便打印输入的每个名称的第一个和最后一个字符吗?
#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;
}
最佳答案
#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;
}
关于c++ - 字符串 vector 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27118991/