Search code examples
c++cioformattingiomanip

printf formatting equivalent in cpp's cout


I am currently a student of Computer Science, and today I received an extra-ordinary assignment, which should be written under C++. I was learning full C until today. This is more like a blind assignment.

In C, I usually use this:

printf("\n\n\t%-30s %-7d liters\n\t%-30s %-7d liters\n\t%-30s %-7d km",
       "Current gasoline in reserve:",
       db.currentGas,
       "Total gasoline used:",
       db.usedGas,
       "Total travel distance:",
       db.usedGas);

Since the assignment's condition is that it should be written in C++, this is what I've tried:

cout << setw(30) << "\n\n\tCurrent gasoline in reserve: "
     << setw(7) << db.currentGas << "litres"
     << setw(30) << "\n\tTotal gasoline used: "
     << setw(7) << db.usedGas << "litres"
     << setw(30) << "\n\tTotal travel distance: "
     << setw(7) << db.travelDistance << "km";

But it looks like there is a differences between C's %-30s and C++'s setw(30)?


Solution

  • Indeed there is a difference, like this:

    Georgioss-MacBook-Pro:~ gsamaras$ g++ -Wall main.cpp
    Georgioss-MacBook-Pro:~ gsamaras$ ./a.out 
    
    
        Current gasoline in reserve:       6litres       
        Total gasoline used:       5litres     
        Total travel distance:       4kmGeorgioss-MacBook-Pro:~ gsamaras$ gcc -W
    Georgioss-MacBook-Pro:~ gsamaras$ ./a.out 
    
    
        Current gasoline in reserve:   6       liters
        Total gasoline used:           5       liters
        Total travel distance:         4       kmGeorgioss-MacBook-Pro:~ gsamaras$ 
    

    But the question is where is the difference?

    setw(30) is equivalent to %30s, but, you have used -30s, which left-aligns the output! In order to get a similar behavior, use std::left, like this:

    cout << "\n\n" << left << setw(30) << "\tCurrent gasoline in reserve: " << left << setw(7) << 6 << "litres\n" << left << setw(30) << "\tTotal gasoline used: " << left << setw(7) << 5 << "litres\n" << left << setw(30) << "\tTotal travel distance: " << left << setw(7) << 4 << "km";