c++ - 字符串 vector 程序

标签 c++ string vector

我创建了一个程序,要求用户输入 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/

相关文章:

c++ - 重新排列数组元素

c++ - 在 C++ 中调用私有(private)方法

java - 错误: cannot find symbol (using replaceAll ) codenameone

javascript - 在字符串中发送 "&"时遇到问题

c++ - 如何从文本文件中分离字符串

c++ - 无法让 toupper 使用 vector

c++ - 您将如何从结构中随机选择路径?

c++ - 一台服务器向一个客户端发送数据。使用 select() 实现非阻塞 I/O

c++ - 验证 QCheckBox stateChanged?

c++ - 使用一个索引 vector 来删除另一个 vector 的那些索引