C++相当于 C 格式化"%3d"是什么?
What is the C++ equivalent to C formatting "%3d"?
我的代码是:
#include<iostream>
using namespace std;
int main()
{
int count=0;
int total=0;
while(count<=10)
{
total=total+count;
cout<<"count"<<"="<<count/*<<','*/<<'t'<<'t'<<"total"<<"="<<total<<endl;
count++;
}
}
使用iostream格式,您需要包括iomanip
标头并使用setw
和setfill
,如下所示:
#include <iostream>
#include <iomanip>
int main() {
using namespace std;
int count=0;
int total=0;
while(count<=10)
{
total=total+count;
cout<<"count"<<"="<<count<<'t'<<'t'<<"total"<<"="<<setfill(' ')<<setw(3)<<total<<endl;
count++;
}
}
C标准库的所有功能在c++中仍然可用。你可以这样写你的程序:
#include <cstdio>
using std::printf;
int main()
{
int count = 0;
int total = 0;
while (count<=10)
{
total = total + count;
printf("count=%3d, total=%3dn", count, total);
count++;
}
}
我个人认为,stdio.h
输出接口几乎总是比iostream
输出接口更容易使用,并产生更可读的代码,特别是对于格式化的数字输出(如在本例中),所以我会毫不犹豫地这样做。iostream
的主要优点是它可以通过operator<<
重载扩展为格式化对象,但是像这样的程序不需要这样做。
请注意,stdio.h
和iostream
输入接口都不适合使用,因为存在令人震惊的标准编码错误,例如定义数字输入溢出以触发未定义行为(我不是在编造这个!)
您可以使用iomanip中的setw
和left
来实现您想要的效果。
#include <iostream>
#include <iomanip>
int main()
{
int count=0;
int total=0;
while(count<=10)
{
total=total+count;
std::cout << "count = " << std::setw(15) << std::right << count << "total = " << total << std::endl;
count++;
}
}
setw
设置下一个"cout印象"的宽度(在本例中为15),left
仅设置左对齐
注意:根据@Zack的建议,你可以在末尾写<< 'n'
而不是<< endl
。由于<< endl
与写入<< 'n' << flush
完全相同,因此在这种情况下不需要刷新
在c++中,IO格式化的方式与C中相同(因为所有C的功能也在c++中存在),或者使用std::setw
std::setprecission
和header中提供的其他c++操作符。
所以这两个都可以:
#include <cstdio>
int main()
{
int count=0;
int total=0;
while( count <= 10)
{
total += count;
printf( "count = %3d, total = %3dn", count++, total);
}
}
或
#include <iostream>
#include <iomanip>
int main()
{
int count=0;
int total=0;
while( count <= 10)
{
total += count;
std::cout << "count = " << std::setw(15) <<
count++ << "total = " << total << std::endl;
}
return 0;
}
您也可以通过imbue
进行自定义格式化,以将自定义facet应用于区域设置(即扩展std::numpunct)。
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- C++避免重复声明的语法是什么
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 实现无开销push_back的最佳方法是什么
- C++从另一个类访问公共静态向量的正确方法是什么
- "throw expression code" 1e7 >返回 d 是什么?投掷标准::overflow_error( "too big" ) : d;意味 着?
- C++中名称篡改的目的是什么
- 在 c++ 中拥有一组结构的正确方法是什么?
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值
- 是什么阻止DOMTimerCoordinator::NextID进入无休止的循环
- 派生类销毁的最佳实践是什么
- 这个语法std::class<>{}(arg1, arg2) 在C++中是什么意思?
- 通过JNI传递数据数组的最快方法是什么
- "using namespace std;"在C++的作用是什么?
- 是什么导致了Unity 3D中的"错误线程异常"?
- 我如何找出3D容器的元素是什么类型
- 在 Vtk 中显示 3D 文本的最佳方式是什么
- 为openGL提供3D坐标的顺序是什么?
- C++相当于 C 格式化"%3d"是什么?
- 在3D场景中存储模型位置的好方法是什么?