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
我不知道,我希望你能告訴我如何得到這個權利。
cout <<「month」<< iValue << endl; 在for循環中寫下它,它將打印所需的輸出。 –