Ten*_*ami 3 c c++ io formatting iomanip
我目前是计算机科学专业的学生,今天我收到了一份非常普通的作业,应该用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);
Run Code Online (Sandbox Code Playgroud)
由于赋值的条件是它应该用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";
Run Code Online (Sandbox Code Playgroud)
但看起来C %-30s和C++ 之间存在差异setw(30)?
确实存在差异,如下所示:
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$
Run Code Online (Sandbox Code Playgroud)
但问题是区别在哪里?
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";
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
390 次 |
| 最近记录: |