4

我需要做的就是将您的全名的输入字符串解析为 3 个单独的名称,这样我就可以获取每个名称的首字母并打印它们。谁能指出我正确的方向?

#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>
using namespace std;    
int main()
{
    string [parsed_output] = fullName.split(" ");
    string firstName = parsed_output[0];
    string middleName = parsed_ouput[1];
    string lastName = parsed_output[2];
    string fullName;
    char firstLetter = firstName[0];
    char middleLetter = middleName[0];
    char lastLetter = lastName[0];
    cout << "Enter your first name, middle name or initial, and last name separated by                              spaces: \n"; 
    cin >> fullName;

    cout << "Your initials are: " << firstLetter << middleLetter << lastLetter << '\n';
    cout << "Your name is: " << firstName << " " << middleName << " " << lastName << '\n';
return 0;
}
4

2 回答 2

3

你让事情变得复杂。'parsed_output[0];' 是什么意思 还是“全名”?你可以这样做:

#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>
using namespace std;    

int main()
{
  string firstName, middleName, lastName;
  cout << "Enter your first name, middle name or initial, and last name separated by                              spaces: \n"; 
  cin >> firstName >> middleName >> lastName;
  char firstLetter = firstName[0];
  char middleLetter = middleName[0];
  char lastLetter = lastName[0];
  cout << "Your initials are: " << firstLetter << middleLetter << lastLetter << '\n';
  cout << "Your name is: " << firstName << " " << middleName << " " << lastName << '\n';
  return 0;
}

整个要点std::cin是,您可以使用提取运算符“>>”获得一个以空格分隔的标记的流。如果您想手动提取名字、中间名和姓氏(如在 hasans 答案中),那么您首先需要整个字符串(一个包含所有 3 个名称和空格的字符串作为限制器)。要读入包含空格的输入,您将使用std::getline(std::cin, fullName)而不是std::cin,因为std::cin将提取输入直到遇到第一个尾随空格。

于 2013-11-04T12:27:16.323 回答
1

您可能想使用 egstd::getline来获取全名,并std::istringstream用于解析:

std::string fullName;
std::getline(std::cin, fullName);

std::istringstream iss(fullName);

std::string firstName, middleName, lastName;
iss >> firstName >> middleName >> lastName;
于 2013-11-04T12:25:59.983 回答