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

浪尽此生 提交于 2019-12-03 19:52:19

问题


In python, the following instruction: print 'a'*5 would output aaaaa. How would one write something similar in C++ in conjunction with std::ostreams in order to avoid a for construct?


回答1:


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');



回答2:


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




回答3:


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";
}


来源:https://stackoverflow.com/questions/11421632/how-to-write-n-copies-of-a-character-to-ostream-like-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!