2017-04-26 35 views
0

這是他們給了我一個任務:如何讓我的程序打印「退出」之後由用戶輸入的所有數據都被輸入

編寫一個程序,反覆要求用戶輸入一個句子並按下Enter鍵。您的程序會將用戶輸入的每個句子存儲到某個容器中。當用戶鍵入「退出」或「退出」時,按字母順序將每個句子打印回屏幕,然後退出。

下面是我到目前爲止有:

#include <iostream> 
#include <string> 
#include <vector> 

using namespace std; 

int main() 
{ 
    string data; 
    vector data; 
    do 
    { 
     cout << "Type a sentence and press enter." 
      "If the word 'exit' is typed, the program will close." << endl; 

     getline(cin, data); 

     // validate if data is not equals to "exit" 
     if (data != "exit" && data != "Exit") 
     { 
      // then type back 
      cout << data << endl; 
     } 
    } 
    while (data != "exit" && data != "Exit"); 

    return 0; 
} 
+1

有沒有想過使用'qsort'函數?或者你可以使用@paddy建議的'std :: sort'。 –

+0

我從來沒有聽說過。我的教授建議我們用矢量容器這樣做。 –

+0

'矢量數據;'?? - >'vector datav;','{while' - >'} while' – BLUEPIXY

回答

1

您需要按照你給的指示:

編寫一個程序,反覆要求用戶輸入一個句子並按下Enter鍵。 您的程序會將用戶鍵入的每個句子存儲到某個容器中。當用戶鍵入「退出」或「退出」時,按字母順序將每個句子打印回屏幕,然後退出。

你沒有在任何地方存儲句子,所以你不能對它們進行排序。你需要做更多的事情是這樣的:

#include <iostream> 
#include <string> 
#include <vector> 
#include <algorithm> 

using namespace std; 

int main() 
{ 
    string line; 
    vector<string> data; 

    do 
    { 
     cout << "Type a sentence and press enter." << endl; 
     cout << "If the word 'exit' is typed, the program will close." << endl; 

     if (!getline(cin, line)) 
      break; 

     // validate if data is equal to "exit" 
     if ((line == "exit") || (line == "Exit")) 
      break; 

     data.push_back(line); // <-- ADD THIS!! 
    } 
    while (true); 

    // sort the data alphabetically 
    sort(data.begin(), data.end()); // <-- ADD THIS!! 

    // then type it back out 
    for(vector<string>::iterator i = data.begin(); i != data.end(); ++i) { 
     cout << *i << endl; 
    } 

    return 0; 
} 
+1

當你提交這個解決方案時,請確保你給雷米充分信用 – pm100

+0

謝謝你一噸雷米!我在這堂課上掙扎了一噸。你也可以解釋「data.push_back(line)」嗎?我感謝每一個輸入,我將信任雷米在我的任務 –

+1

在你的書/ C++參考中查找std :: vector;它應該解釋push_back成員函數。 –

0

當尋找某種類型的排序功能,我建議使用std:sort()的,因爲它是爲C++創建。您可以使用qsort(),但不是因爲它在C

std:sort()函數做的是按升序排列一系列元素,這就是你想要的。使用此功能時使用的標頭爲#include <algorithm>。有關此功能的更多信息,請致電check this link out

相關問題