2017-06-29 114 views
0

這是我第一次嘗試理解向量,所以請裸露在我身邊(我知道這是新手),我已經閱讀並重新閱讀代碼,但是我找不到合理的結論:爲什麼在運行時,在開始和結束時間之間沒有創建新行。讚賞積極和消極的建議。endl似乎沒有執行

#include <iostream> 
#include <string> 
#include <vector> 
using namespace std; 

int main() { 
    //start time and end time of shift 
    vector <int> vstart; 
    vector <int> vend; 
    vector <string> days_of_week = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; 
    int start, end; 
    while (cin >> start) { 
     vstart.push_back(start); 
    } 
    while (cin >> end) { 
     vend.push_back(end); 
    } 

    for (string d : days_of_week) { 
     cout << d << "\t"; 
    } 
    cout << endl << "---------------------------------------------------------\n"; 
    for (int s : vstart) { 
     cout << s << "\t"; 
    } 
    cout << endl; 
    for (int e : vend) { 
     cout << e << "\t"; 
    } 
    cout << endl; 
}  
+2

對於某些指定的輸入,您能向我們展示預期的和實際的輸出嗎? –

+0

如果你想避免多餘的複製操作,你應該使用'for(const string&d:days_of_week)'。 – voltento

+0

輸出結果應該列出days_of_week中定義的星期幾,用製表符隔開,然後是破折號屏障,然後是換行符和每個換行的開始時間,後面跟着換行符和每個換行的結束時間 – NewToThis

回答

1

讓我們來看看這部分代碼。

while (cin >> start) { 
    vstart.push_back(start); 
} 
while (cin >> end) { 
    vend.push_back(end); 
} 

在第一個循環,你在讀取值,直到cin>>start到達檔案結尾的字節,或以不同的方式失敗。但是你不清楚那個失敗狀態。 您必須致電cin.clear();才能在第二個循環中讀取新輸入。

while (cin >> start) { 
    vstart.push_back(start); 
} 
cin.clear(); 
while (cin >> end) { 
    vend.push_back(end); 
} 

延伸閱讀:Why would we call cin.clear() and cin.ignore() after reading input?

1

while循環將只要執行,因爲它可以成功地提取int值。它不知道在閱讀7個數字後停止,並將所有輸入放入vstart

while (cin >> start) { 
    vstart.push_back(start); 
} 

我想你想要這樣的for循環,其中包括邏輯讀取7值後停止。

for (int i = 0; (i < 7) && (cin >> start); ++i) { 
    vstart.push_back(start); 
}