2012-04-23 63 views
0

我在這裏要做的是寫一個函數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 ; 
} 
+1

你嘗試,以及如何爲你預期的那樣,他們不起作用怎麼投入? – sarnold 2012-04-23 04:14:16

+2

這個代碼將正常運行..在這裏看到:http://ideone.com/eISah – Naveen 2012-04-23 04:14:50

+4

我敢打賭,你使用的是Windows。嘗試打開cmd.exe並從命令行調用您的程序,而不是雙擊它。這樣窗口在程序終止時不會消失。 – zmccord 2012-04-23 04:23:56

回答

3

您的代碼似乎工作,但我個人認爲我會寫不同了一點:

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(); 
} 
+0

謝謝我很感激我的計算機編程和科學181有時你先了解硬盤的方式 – 2012-04-23 05:12:28

0

我有上面納文同意,沒有問題在網上嘗試編譯此代碼時,見http://codepad.org/PwDtkUEu enter image description here 你得到,要歸功於你的編譯器的任何問題,請嘗試重新建立你的項目。

+0

泰:)我感謝幫助 – 2012-04-23 05:14:05

+0

@KcNorth點擊甚至:「泰:)我欣賞的幫助」是最好的表達[‘通過點擊複選框大綱的回答’的左側(http://stackoverflow.com/faq#howtoask)。 – Johnsyweb 2012-04-23 11:05:37