C ++将输入字符串解析为变量

时间:2013-11-04 12:20:25

标签: c++ string parsing

我需要做的就是将你的全名的输入字符串解析成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;
}

3 个答案:

答案 0 :(得分:1)

您可能想要使用例如std::getline获取全名,std::istringstream获取解析:

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

std::istringstream iss(fullName);

std::string firstName, middleName, lastName;
iss >> firstName >> middleName >> lastName;

答案 1 :(得分:1)

你正在制造复杂的方法。 'parsed_output [0];'是什么意思?'和'fullName'无论如何?你可以这么做:

#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的整个点是,您使用提取运算符'&gt;&gt;'得到一个到空格分隔的标记的流。如果你想提取第一个,中间的和手写的姓氏(比如hasans的答案),那么你首先需要整个字符串(一个包含所有3个名字和空格作为限制器的字符串)。要读入包含空格的输入,您将使用std::getline(std::cin, fullName)而不是std::cin,因为std::cin将提取输入,直到遇到第一个尾随空格。

答案 2 :(得分:0)

string temp = fullname;

string firstName = temp.substr(0, temp.find(" "));

temp = temp.substr(temp.find(" ")+1);
string middleName = temp.substr(0, temp.find(" "));

string lastName = temp.substr(temp.find(" ")+1);