baoky chen
baoky chen

Reputation: 837

C++ Get Current date output weird result

My output is unreadable, all i wanted to do is assign the day month year into a string.

if i cout them by now->tm_year+1900 , it works, but if i assign it to a string and cout later, it output like this. how do i change my code so i can assign the value to string without losing reference later on cout.

Terminal:

Date is 

My code:

int main()
{
//get today date
string year,month,day;

/* Output 6 month frame for appointment booking*/
 time_t t = time(0);   // get time now
 struct tm * now = localtime( & t );

year = now->tm_year + 1900;
month = now->tm_mon + 1;
day = now->tm_mday;

cout << "Date is " << year << month << day << endl;

return 0;
}

Upvotes: 0

Views: 268

Answers (2)

Ralph Tandetzky
Ralph Tandetzky

Reputation: 23610

You can write int instead of string in your code file.

Upvotes: 0

eq-
eq-

Reputation: 10096

You can't assign integers to strings (well, you can, but it doesn't quite do what you'd expect); you have to convert them first:

std::string year = std::to_string(now->tm_year + 1900);

Other options include storing the number as an integer; you can print integers, too:

int year = now->tm_year + 1900;

Upvotes: 2

Related Questions