C ++将输入字符串解析为变量 [英] C++ Parsing input string to variables

查看:252
本文介绍了C ++将输入字符串解析为变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要做的就是将您的全名输入字符串解析为3个独立的名称,这样我就可以将每个名称的首字母缩写并打印出来.谁能指出我正确的方向?

All i need to do is to parse the input string of your full name, into 3 separate names so I can take the first initials of each and print them. Can anyone point me in the right direction?

#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;
}

推荐答案

您可能想使用例如 std::getline 获取全名,然后

You may want to use e.g. std::getline to get the full name, and std::istringstream for the parsing:

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

std::istringstream iss(fullName);

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

这篇关于C ++将输入字符串解析为变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆