cpp 的 cout 中的 printf 格式等价物

printf formatting equivalent in cpp's cout

我现在是计算机专业的学生,​​今天接到了一个特别的作业,应该是用C++写的。直到今天,我一直在学习完整的 C。这更像是一个盲目的作业。

在C中,我通常这样使用:

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);

由于作业的条件是它应该用 C++ 编写,这就是我尝试过的:

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";

但是 C 的 %-30s 和 C++ 的 setw(30) 之间似乎有区别?

printf 中的减号表示左对齐。

要在 C++ 中做到这一点,您需要 std::left

确实有区别,像这样:

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$ 

但问题是哪里有区别?

setw(30)等价于%30s但是,你用了-30s,它左对齐输出!为了获得类似的行为,请使用 std::left,如下所示:

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";

在 C++20 中,您将能够为此使用 std::format,这很容易从 printf:

翻译过来
std::cout << std::format(
       "\n\n\t{:30} {:<7} liters\n\t{:30} {:<7} liters\n\t{:30} {:<7} km",
       "Current gasoline in reserve:",
       db.currentGas,
       "Total gasoline used:",
       db.usedGas,
       "Total travel distance:",
       db.usedGas);

在此期间您可以使用 the {fmt} library, std::format is based on. {fmt} also provides the print function that makes this even easier and more efficient (godbolt):

fmt::print(
       "\n\n\t{:30} {:<7} liters\n\t{:30} {:<7} liters\n\t{:30} {:<7} km",
       "Current gasoline in reserve:",
       db.currentGas,
       "Total gasoline used:",
       db.usedGas,
       "Total travel distance:",
       db.usedGas);

免责声明:我是 {fmt} 和 C++20 的作者 std::format