'How to write statement that deletes extra space in C++?

I have been working on a project. I am limited to using a few libraries so any additional library would not be helpful. I am building a project, but I am noticing an extra space after the last number when the calendar is finished. How do I fix this extra spacing issue?

//extracted...
         if (day >= 9)
         {
            std::cout << day;
         }
         else 
          std::cout << day << " ";
          std::cout << " ";
      }
   }

c++


Solution 1:[1]

Version in C: (it uses printf so maybe not what you want)

void printcalendarmonth(int month, int year)
{
    int indent;
    int nspace = 0;
    
    Monthinfo m = getmonthinfo(month, year);
    
    printf("\n%*s %d\n\n", 12, m.name, year);  // ex.) January 2012
    char weekTitle[] = "  S  M Tu  W Th  F  S";
    int spacing = sizeof(weekTitle)/7;

    printf("%s\n", weekTitle);
    
    indent = m.daystart * spacing;    // m.daystart = weekday number first day is starting on: ex.) Sunday = 0 or 1 I forgot sorry lol
    for (int i = 1; i <= m.days; i++) {
        printf("%*.d", indent, i);
        nspace += indent;
        indent = spacing;
        if (nspace >= spacing*7) {
            printf("\n");
            nspace = 0;
        }   
    }
    printf("\n");
}

Solution 2:[2]

std::cout << std::setw(2) << day might get rid of if (day >= 9) stuff.

Then to write number with some separator, I tend to use following pattern

const char* sep = "";
for (auto e : some_list) {
    std::cout << sep << e;
    sep = ", "; // or any separator
}

Resulting into

const char* sep = "";
for (day = 1; day <= days_per; day++)
{
    std::cout << sep << std::setw(2) << day;
    sep = " ";
    if (++count > 6)
    {
        std::cout << '\n';
        count = 0;
        sep = "";
    }
}

Demo

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Jarod42