在C中将字符串乘以int

新手上路,请多包涵

我该怎么做,这样当我

string s = ".";

如果我做

cout << s * 2;

会不会一样

cout << "..";

?

原文由 skittles sour 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 922
2 个回答

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

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

#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

原文由 ForEveR 发布,翻译遵循 CC BY-SA 3.0 许可协议

像 JRG 一样,但在一行中

std::cout << std::string(70,'-') << std::endl;

这将创建一个字符串,用 - (破折号)填充,长度为 70 个字符,并在末尾用 std::endl 换行;

原文由 Guilherme Ratib 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题