2017-04-26 114 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

相关问题