Home > front end >  My program wont read a 0 before the bookcase number in c
My program wont read a 0 before the bookcase number in c

Time:10-28

I'm trying to write a program that displays book names and their bookcase numbers.

However, I need to make sure there should be a 0 set for all the bookcase numbers that aren't a 3-digit number. For example, the output should show 2/056, but instead it is showing me 2/56.

Can anyone tell me how I can put a 0 before all the 2-digit numbers and not the 3-digit numbers? It should be done using setfill().

std::ostream& Book::write(std::ostream& ostr, bool onScreen) const
{
    if (onScreen)
    {
        if (*this)
        {
            ostr << m_BookTitle;
            ostr << setw(42 - strlen(m_BookTitle)) << setfill(' ');
            ostr << "| " << m_AuthorName;

            ostr << setw(27 - strlen(m_AuthorName)) << setfill(' ');

            ostr << "| " << m_ShelfNumber << "/" << m_BookcaseNumber;
        }
        else
        {
            ostr << "Invalid Book Record ................... | ........................ | .....";
        }
    }
    else
    {
        if (*this)
        {
            ostr << m_BookTitle << "," << m_AuthorName << "," << m_ShelfNumber << "/" << m_BookcaseNumber;
        }
        else {
            ;
        }
    }

    return ostr;
}

CodePudding user response:

Put ostr << setw(3)<<setfill('0') before you print the number that supposted to be 3 digit

CodePudding user response:

ostr << setw(27 - strlen(m_AuthorName)) << setfill(' ');

You do know about setfill, so why are you asking?

I wonder if you know what it's actually for? You're using it to replicate a space and calculating the number of spaces based on the field length. But that's insane, since you should just set the width you want m_AuthorName to be extended to. You appear to want the field justified to the left of a 27-character zone, with spaces filling the rest.

ostr << setw(27) << left << m_AuthorName;

is what you want here.

For the number, you want to fill with 0 characters.

Look at the examples on the bottom of this reference page.


I don't see all the code, but I wonder why you call the C function strlen to get the length of a string. Are you not using std::string to hold these values?

  •  Tags:  
  • c
  • Related