2017-04-19 25 views
1

我不得不編寫一個程序,要求用戶在命令提示符中輸入一個句子。如果用戶鍵入單詞「退出」或「退出」(不帶引號和全部小寫),那麼程序應該退出。否則,程序應該輸出用戶鍵入的內容並要求用戶鍵入其他內容。我瞭解如何獲取該句子,但我不知道如何使程序退出命令提示符。請幫助?如果輸入「exit」這個單詞,我該如何在命令promt中做出這個退出?

#include <iostream> 
#include <string> 

using namespace std; 


int main() 
{ 
    string data; 

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

    getline(cin, data); 
    cout << data; 


    return 0; 
} 
+2

使用一個循環條件 – Ceros

+3

看起來像[do-while循環]的好工作(http://en.cppreference.com/w/cpp/language/do)。 –

+0

正在退出你想要什麼,不能做什麼?當到達'return 0;'時會發生什麼?這不是你想要的嗎?或者不存在你想要的,在這種情況下使用循環,正如其他人所評論的那樣。或者你想要命令提示符退出?在這種情況下,您可能需要以程序結束時關閉的方式創建命令提示符。那將是一個空殼問題。 – Yunnosch

回答

1

你可以試試下面的代碼:

#include <iostream> 
#include <cstdlib> 
#include <boost/algorithm/string.hpp> 

using namespace std; 

int main() { 
    string data; 
    while(true) { 

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

    getline(cin, data); 
    if (boost::iequals(data, "exit")) 
     exit(0); 
    else 
     cout << data; 
    } 
} 
+3

我可能更傾向於'break'而不是'exit(0)',但是是的。 –

+1

爲什麼使用'boost :: iequals()'而不是'std :: string :: operator =='或'std :: strcmp()'或類似的東西?並非每個人都安裝了Boost。 –

3

你可以比較的價值與 「退出」 接收數據。 如果你只想顯示類型回用戶數據,試試這個:

int main() { 
    string data; 

    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 equals to "exit" 
    if (data.compare("exit") != 0) { 
     cout << data; 
    } 

    return 0; 
} 

如果你想在「退出」時輸入型背使用輸入,試試這個:

int main() { 
    string 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.compare("exit") != 0) { 
      // then type back 
      cout << data << endl; 
     } else { 
      // else interrupt while 
      break; 
     } 
    // will run while break or return be called 
    } while (true); 

    // terminate the program 
    return 0; 
} 
+0

第二個例子更好地使用'do/while'循環來處理。不需要重複兩次相同的代碼。 –

相關問題