Search code examples
c++timeformatting

How to Add 0 infront of an int without external library c++


What i Hope to accomplish

So i have a class with date and time and i am using a struct in which year, month, date are integers I want when the user enters a number for example 3 it must output 03 but must be in an int format without using the IOMANIP library or fmt library as when i use these library i get 'error time does not have a type'

Please Help How can i get a 0 infront of months and days to be stored in a variable whilst still being an int;

I have tried the setw But does not work as mentioned above

So what i have tried was to store it in a pointer and vector

I have a class called vehicle with struct date and time

struct time
{
    int hh;
    int mm;
    int ss;
    char col1;
    char col2;
};
struct date
{
  int day;
  int month;
  int year;
  char sym1;
  char sym2;
};

class vehicle
{
    string pltno;
    int type;
    date dt;
    time arrive;
    time departure;

Code I have

vector<vehicle> vehleft(100);
int static totalvehicle=0,totalcar=0,totalbike=0,totalamt=0,i=0,z=0;

fstream file;

void vehicle::addVehicle()
{

      vehicle *v = new vehicle;
      cin.ignore();
      cout<<"Enter vehicle number : ";
      std::getline(cin, v->pltno);
      cout<<"Enter arrival time in hours minutes and seconds : ";
      cin>>v->arrive.hh>>v->arrive.col1>>v->arrive.mm>>v->arrive.col2>>v->arrive.ss;
      cout<<"Enter date in day month and year: ";
      cin>>v->dt.day>>v->dt.sym1>>v->dt.month>>v->dt.sym2>>v->dt.year;

What i tried to do was use the setw and setfill to add a 0 infront but when i do so i get an error that 'time is not a type' this happens whenever i include the ctime library or Iomanip library.

Basically I want v->dt.day and v->dt.month to assign the user input as of this moment if the number is 3 it will stay as 3 and not 03 which is the format i want

Update

When I input 10 for example in month when it is outputed it says 0 instead of 10?


Solution

  • setw works in conjunction with setfill so something like

    std::cout << std::setw(2) << std::setfill('0') << day; 
    

    might work for you. See also https://en.cppreference.com/w/cpp/io/manip/setfill