C++ Parsing input string to variables

29,780

Solution 1

You're making things way to complicated. What's the meaning of 'parsed_output[0];' and 'fullName' anyway? You could just do:

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

The whole Point of std::cin is, that you get an stream to space separated tokens with the extraction operator '>>'. If you want to extract the first, middle & last names by Hand (like in hasans answer), then you would need the whole string in the first place (a string with all 3 names and whitespaces as limiter). To read in input with containing spaces you would use std::getline(std::cin, fullName) instead of std::cin, because std::cin will extract the Input until the first trailing whitespace is encountered.

Solution 2

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;
Share:
29,780
user2939276
Author by

user2939276

Updated on November 05, 2020

Comments

  • user2939276
    user2939276 over 3 years

    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;
    }
    
  • crashmstr
    crashmstr over 10 years
    Won't std::cin >> fullName stop at whitespace? You would need to use std::getline to require parsing.