User2010101
User2010101

Reputation: 92

Read formatted input with cin?

Let's imagine this input : 01202014 (ddmmyyyy) .

My question is :

How can I read the input to three separated variables using pure C++ ?

As far as I know this would work , but this would be a mix C/C++ and I'm wondering if there is any solution that is pure C++.

 #include <iostream>

 int main()

 {


 int mm, dd, yy;

 scanf_s("%2d%2d%4d", &mm, &dd, &yy);
 //How can I do the same with Cin? std::cin 
 std::cout << mm << "/" << dd << "/" << yy;


 system("pause");

 }

Example :

Input : 01232009

Objective :

mm = 1;
dd = 23;
yy  = 2009 

Upvotes: 1

Views: 1716

Answers (1)

P0W
P0W

Reputation: 47794

Since you need in DDMMYYYY format, you can have following :

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

int dd,mm,yy;
if ( date.size() ==  8 ) // Other checkings left for you
{   
    mm = std::stoi( date.substr(0,2) );   
    dd = std::stoi( date.substr(2,2) ); 
    yy = std::stoi( date.substr(4) ); 

    std::cout << dd << "/" << mm << "/" << yy ;
}

See Here

And now please don't change question !

Upvotes: 4

Related Questions