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

标签 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;
}

最佳答案

你让事情变得复杂了。 “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 将提取输入,直到遇到第一个尾随空格。

关于C++ 将输入字符串解析为变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19767644/

相关文章:

c++ - 访问 vector 元素的类中的 "this"指针

c - 这会在复制字符串时起作用吗?

string - Gusfield 对动态规划算法的描述是否有错误,该算法用于寻找具有恒定空位惩罚的全局比对?

Linux shell 命令反转变长文本记录的字段顺序

c++ - 运算符重载 : cannot add two pointers

c++ - 在 Xcode 中的特定行显示运行时错误消息

java - 在此程序中无法将 String 转换为 int

从 lisp 中的字符串解析数字

c - 如何解析Nginx配置文件?

c++ - 使用 OpenCV 打开网络摄像头并使用 QLabel 显示它 - 白色窗口