How to write 'n' copies of a character to ostream like in python

后端 未结 4 915
半阙折子戏
半阙折子戏 2021-01-02 00:54

In python, the following instruction: print \'a\'*5 would output aaaaa. How would one write something similar in C++ in conjunction with std:

相关标签:
4条回答
  • 2021-01-02 01:18

    Use some tricky way: os << setw(n) << setfill(c) << ""; Where n is number of char c to write

    0 讨论(0)
  • 2021-01-02 01:25

    In C++20 you'll be able to use std::format to do this:

    std::cout << std::format("{:a<5}", "");
    

    Output:

    aaaaa
    

    In the meantime you can use the {fmt} library, std::format is based on. {fmt} also provides the print function that makes this even easier and more efficient (godbolt):

    fmt::print("{:a<5}", "");
    

    Disclaimer: I'm the author of {fmt} and C++20 std::format.

    0 讨论(0)
  • 2021-01-02 01:29

    You can do something like that by overloading the * operator for std::string. Here is a small example

    #include<iostream>
    #include<string>
    std::string operator*(const std::string &c,int n)
    {
        std::string str;
        for(int i=0;i<n;i++)
        str+=c;
        return str;
    }
    int main()
    {
        std::string str= "foo";
        std::cout<< str*5 <<"\n";
    }
    
    0 讨论(0)
  • 2021-01-02 01:32

    The obvious way would be with fill_n:

    std::fill_n(std::ostream_iterator<char>(std::cout), 5, 'a');
    

    Another possibility would be be to just construct a string:

    std::cout << std::string(5, 'a');
    
    0 讨论(0)
提交回复
热议问题