在 C++ 中将字符串乘以 int [英] Multiplying a string by an int in C++

查看:36
本文介绍了在 C++ 中将字符串乘以 int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我这样做时,我该怎么做

What do I have to do so that when I

string s = ".";

如果我这样做

cout << s * 2;

会不会一样

cout << "..";

?

推荐答案

不,std::string 没有 operator *.您可以将 (char, string) 添加到其他字符串.看看这个 http://en.cppreference.com/w/cpp/string/basic_string

No, std::string has no operator *. You can add (char, string) to other string. Look at this http://en.cppreference.com/w/cpp/string/basic_string

如果你想要这种行为(没有建议),你可以使用这样的东西

And if you want this behaviour (no advice this) you can use something like this

#include <iostream>
#include <string>

template<typename Char, typename Traits, typename Allocator>
std::basic_string<Char, Traits, Allocator> operator *
(const std::basic_string<Char, Traits, Allocator> s, size_t n)
{
   std::basic_string<Char, Traits, Allocator> tmp = s;
   for (size_t i = 0; i < n; ++i)
   {
      tmp += s;
   }
   return tmp;
}

template<typename Char, typename Traits, typename Allocator>
std::basic_string<Char, Traits, Allocator> operator *
(size_t n, const std::basic_string<Char, Traits, Allocator>& s)
{
   return s * n;
}

int main()
{
   std::string s = "a";
   std::cout << s * 5 << std::endl;
   std::cout << 5 * s << std::endl;
   std::wstring ws = L"a";
   std::wcout << ws * 5 << std::endl;
   std::wcout << 5 * ws << std::endl;
}

http://liveworkspace.org/code/52f7877b88cd0fba4622fab885907313

这篇关于在 C++ 中将字符串乘以 int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆