C++ 中继器问题:(

C++ 中继器问题:(,c++,string,C++,String,这里我要做的是编写一个函数repeat,它接受一个字符串和一个正整数n并返回该字符串重复n次。因此repeat(“fho”,3)将返回字符串“hohoho”。但是,下面的测试程序运行,但未显示结果或挂起。我尝试添加系统暂停,但没有帮助。我缺少什么 #include <string> #include <iostream> std::string repeat( const std::string &word, int times ) { std::strin

这里我要做的是编写一个函数
repeat
,它接受一个字符串和一个正整数n并返回该字符串重复n次。因此
repeat(“fho”,3)
将返回字符串“hohoho”。但是,下面的测试程序运行,但未显示结果或挂起。我尝试添加系统暂停,但没有帮助。我缺少什么

#include <string>
#include <iostream>
std::string repeat( const std::string &word, int times ) {
   std::string result ;
   result.reserve(times*word.length()); // avoid repeated reallocation
   for ( int a = 0 ; a < times ; a++ ) 
      result += word ;
   return result ;
}

int main( ) {
   std::cout << repeat( "Ha" , 5 ) << std::endl ;
   return 0 ;
}
#包括
#包括
std::string repeat(常量std::string和word,整数倍){
std::字符串结果;
result.reserve(times*word.length());//避免重复重新分配
for(int a=0;astd::cout我必须同意上面的Naveen。在联机编译器中尝试时,此代码没有问题。请参阅

您遇到的任何问题都必须归咎于您的编译器。请尝试重新编译您的项目。

我必须同意上面的Naveen。在联机编译器中尝试时,此代码没有问题。请参阅
您遇到的任何问题都一定是由于您的编译器造成的。请尝试重新编译您的项目。

您的代码似乎可以正常工作,但就个人而言,我认为我的编写方式会有所不同:

std::string repeat(std::string const &input, size_t reps) { 
    std::ostringstream result;

    std::fill_n(
        std::ostream_iterator<std::string>(result), 
        reps, 
        input);

    return result.str();
}
std::string repeat(std::string const&input,size\t reps){
std::ostringstream结果;
标准:填充(
std::ostream_迭代器(结果),
代表们,
输入);
返回result.str();
}

您的代码似乎可以正常工作,但就我个人而言,我认为我应该写得有点不同:

std::string repeat(std::string const &input, size_t reps) { 
    std::ostringstream result;

    std::fill_n(
        std::ostream_iterator<std::string>(result), 
        reps, 
        input);

    return result.str();
}
std::string repeat(std::string const&input,size\t reps){
std::ostringstream结果;
标准:填充(
std::ostream_迭代器(结果),
代表们,
输入);
返回result.str();
}

您尝试了哪些输入,它们是如何工作的?这些代码运行正常。请看这里:我打赌您是在Windows上。尝试打开cmd.exe并从命令行调用您的程序,而不是双击它。这样,当您的程序终止时,窗口不会消失。lol我在Windows上,是的,它会消失当我将其加载到在线编译器中时工作非常奇怪,Outlook会关闭它,因此即使使用系统也会单击(“暂停”)您尝试了哪些输入,它们是如何工作的?这些代码运行正常。请看这里:我打赌您是在Windows上。尝试打开cmd.exe并从命令行调用您的程序,而不是双击它。这样,当您的程序终止时,窗口不会消失。lol我在Windows上,是的,它确实可以工作当我把它加载到在线编译器中时,很奇怪Outlook会关闭它,所以即使使用系统也要单击(“暂停”)谢谢我很感激我在计算机编程与科学181有时你先学习困难的方法谢谢我很感激我在计算机编程与科学181有时你学习困难的方法first@KcNorth:“泰:)“我感谢你的帮助”表达得最好。@KcNorth:“Ty:)我感谢你的帮助”表达得最好。