c++ - 如何在 .txt 文件中以垂直线格式化特定文本?

标签 c++ format

我已经设法使用此示例代码将 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/

相关文章:

javascript - 如何通过一次调用 format() 格式化 04Apr

r - 无法将此 excel 文件导入 R

EC 公钥/私钥的文件格式?

c++ - 列表控件中的 MFC 对话框组合框

c++ - 将模板仿函数传递给模板 std::function

ios - 这个字符串是什么格式?

oop - 一个对象拒绝它自己是正确的吗?

c++ - 嵌套在类模板中的类 X 的 operator<<(ostream&, X)

c++ - QGridLayout 具有不同大小的单元格

c++ - 为什么我的二进制搜索没有返回要显示的名称?