我已经设法使用此示例代码将 1 到 10 之间的一些随机数据写入文件:
for (int i = 1; i <= size; i++)
{
type = rand () % 3;
switch (type)
{
case 0: afile << rand () % 10;
break;
case 1: afile << rand () % 10;
afile << "\t\t";
afile << rand () % 10;
break;
case 2: afile << rand () % 10;
afile << "\t\t";
afile << rand () % 10;
afile << "\t\t";
afile << rand () % 10;
}
afile << "\t\t" << "// Possible type " << i << endl;
}
我的输出是这样的:
8 // Possible type 1
1 7 // Possible type 2
4 0 3 // Possible type 3
如何设置评论的格式,使其保持在垂直线上,如下所示:
8 // Possible type 1
1 7 // Possible type 2
4 0 3 // Possible type 3
我试过 setw
但没有成功,因为我正在运行一个循环,这使得 setw
在这里不适用。有什么功能可以帮助我解决这个问题吗?
最佳答案
一种选择是更新您的 case
语句,如下所示:
switch (type)
{
case 0: afile << rand () % 10;
afile << "\t\t\t\t\t\t";
break;
case 1: afile << rand () % 10;
afile << "\t\t";
afile << rand () % 10;
afile << "\t\t\t\t";
break;
case 2: afile << rand () % 10;
afile << "\t\t";
afile << rand () % 10;
afile << "\t\t";
afile << rand () % 10;
afile << "\t\t";
}
关于c++ - 如何在 .txt 文件中以垂直线格式化特定文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31340083/