每隔n个字符打印一行换行符

Print a newline every n characters

本文关键字:一行 换行符 字符 打印 每隔      更新时间:2023-10-16

我试图打印一个字符数组,但我想在固定数量的字符后打印一个换行符。到目前为止,我只能在读取第一个固定数量的字符后打印一行换行符。有人能给我指正确的方向吗?

    for ( int i = 0; i < (m_nWidth*m_nHeight); i++) {
        if (i != m_nWidth)
            cout << pMyPointer[i];
        else
        {
            printf("n");
        }
    }
if( i % n == 0 && i != 0 ) printf("n");

其中n是换行之间的字符数。


编辑:完整上下文:

#include <iostream>
int main()
{
    const int n = 5;
    const std::string str("abcdefghijklmnopqrstuvwxyz");
    for (int i=0 ; i<str.size() ; ++i)
    {
        if (i%n == 0 && i != 0)
            std::cout << 'n';
        std::cout << str[i];
    }
    std::cout << std::endl;
    return 0;
}

您可以使用模块运算符:

if(i % n == 0)
 printf("n");