r/programminghelp • • Apr 13 '24

C++ Having trouble stringing 3 integers from a struct. C++ Beginner

I'm very new and just decided to change the integers into strings.

The integers in mind were the month day year values.

https://pastebin.com/WgFQSTHZ

month, day, and year were changed from int to string to get the code to run. maybe im right to have them as strings? idk, is there a way to do this with integers?

0 Upvotes

22 comments sorted by

View all comments

Show parent comment

2

u/DDDDarky Apr 13 '24

Nice, if you want to take it further, it is a good practice to initialize your variables, like this:

games myGame1{};

and

int hoursPlayed{};

etc.

(the {} is the important part, it default-initializes variables, so your ints will be 0, without it, they can hold any "random" value before you assign a value into them)

1

u/Creepy_Version_6779 Apr 13 '24

ok that's very helpful, thank you!

2

u/DDDDarky Apr 13 '24

oh btw, one more thing, generally, you might not want to start your integers with 0.

For example, you might be surprised to learn that

std::cout << 012

will actually print 10.

That is because integers starting with 0 denote octal numbers (base 8, not standard base 10)

1

u/Creepy_Version_6779 Apr 13 '24 edited Apr 13 '24

how would i go about it if i wanted a 0 before a 4 in the console?

i could do this or is there a better way?

std::cout << "0" << var{4};

i also put some comments on it to help me remember this stuff. :)

2

u/DDDDarky Apr 13 '24

Yes, you could use format, like this:

#include <format>
...
std::cout << std::format("{:02}", 12);

(make sure you compile with at least C++20)

The {:02} is a formatting string, that basically means take argument, format it to 2 places and fill it with 0s.

1

u/Creepy_Version_6779 Apr 13 '24

oh wow thats really cool. took me a bit to figure it out but ima play around with it more tomorrow. That seems very useful.

1

u/Creepy_Version_6779 Apr 14 '24

small update. I got rid of std::to_string() and replaced it with std::format() entirely.

1

u/DDDDarky Apr 14 '24

Sure, that's not a bad idea, I assume you do something like this:

myGame1.lastDatePlayed = std::format("{:02},{:02},{}", myGame1.month, myGame1.day, myGame1.year);

1

u/Creepy_Version_6779 Apr 14 '24

here's the code. not sure if im using it right based on what you have though.

1

u/DDDDarky Apr 14 '24

It is not used wrong, but it depends what do you expect your lastDatePlayed string to look like.

For example, now, if you assign month=12, day=1, year=2024, you will get a string that looks like this:

012.1.2024

I have a feeling that is not what you really want.

1

u/Creepy_Version_6779 Apr 14 '24

This is what I get when I run it.

Game 1: Content Warning
Hours Played: 68h
Last Played(month,day,year): 04.13.2024

Game 2: Squad
Hours Played: 70h
Last Played(month,day,year): 04.06.2024

Game 3: Counter-Strike 2
Hours Played: 47h
Last Played(month,day,year): 04.03.2024
→ More replies