2017-08-12 48 views
0

這裏是我的代碼:控制COUT在for循環中

#include <iostream> 
#include <string> 
#include <sstream> 

using namespace std; 

int main() 
{ 

stringstream os; // Initialize stringstream "os" 
string mValue = "month"; // Initialize mValue "month" 
int iValue = 1; // Initialize iValue "1" 

for(int iValue = 1; iValue < 13; ++iValue) // Iteration 1: 1 < 12 so execute the following: 
{ 
    os << mValue << "" << iValue; // Glue mValue and iValue together 
    cout << os.str() << endl; // Print glued mValue and iValue 
} 

return 0; 

} 

這將導致以下的輸出:

month1 
month2month2 
month3month3month3 
month4month4month4month4 
month5month5month5month5month5 
month6month6month6month6month6month6 
month7month7month7month7month7month7month7 
month8month8month8month8month8month8month8month8 
month9month9month9month9month9month9month9month9month9 
month10month10month10month10month10month10month10month10month10 
month11month11month11month11month11month11month11month11month11month11 
month12month12month12month12month12month12month12month12month12month12month12 

所需的輸出是:

month1 
month2 
month3 
month4 
month5 
month6 
month7 
month8 
month9 
month10 
month11 
month12 

作爲一個小白在編碼方面,我明白爲什麼會發生這種情況,但我不知道如何解決這個問題。我試圖把cout放在for循環之外,但是結果在

month1month2month3month4month5month6month7month8month9month10month11month12 

我不知道,我希望你能告訴我如何得到這個權利。

+1

cout <<「month」<< iValue << endl; 在for循環中寫下它,它將打印所需的輸出。 –

回答

0

將cout放置在循環之外後,您需要將下一行轉義序列添加到for循環中的os值。

os << mValue << "" << iValue << "\n"; 
+0

非常感謝帕夏! – TwoGoldFish