Hello, I am trying to take in user input using getline(), but I am having an issue with the function.
I want users to input a name and an ID associated with their name where the name is inputted with double quotes and the ID has to be 8 digits long. For example:
"Bob Vance" 12345678
"Dwight Schrute" 12344321
Right now I have both the ID and name working separately, but I am confused on how to get this input from the user in one line and then separate the name and ID to its corresponding variable. I tried using getline() but that does not seem to work.
#include <iostream>
#include <string>
#include <regex>
int main()
{
std::cout << "enter the name in double quotes and the 8 digits ID: " ;
std::string input ;
if( std::getline( std::cin, input ) )
{
// optional white space, quote, name having one or more non-quote characters (capture 1), quote,
// optional white space, 8 decimal digits (captrure 2), optional white space
const std::regex input_re( "\\s*\"([^\"]+)\"\\s*(\\d{8})\\s*" ) ;
std::smatch match ;
if( std::regex_match( input, match, input_re ) ) // if the input matches
{
const std::string name = match[1] ; // pick up name from capture 1
constint id = std::stoi( match[2] ) ; // and id as an integer from capture 2
std::cout << "name: " << name << "\nid: " << id << '\n' ;
}
else std::cout << "invalid input\n" ;
}
}