2014-11-25 83 views
-1

我有一個關於一個函數的問題,它需要一個字符串(命令,名字和姓氏),並根據輸入的內容執行。我的函數還有其他幾個if語句,如果輸入被認爲是無效的,我該如何讓用戶輸入另一個命令?謝謝調用自己的C++輸入函數

EXAMPLE_INPUT = "CREATE John Doe" 

std::string get_input(std::string& s) 
{ 
    std::string raw_input; 
    std::getline(std::cin, raw_input); 
    std::istringstream input(raw_input); 

    std::string command; 
    std::string first_name; 
    std::string last_name; 

    input >> command; 
    input >> first_name; 
    input >> last_name; 

    //what do I return? I can't return all 3 (command, first, last) 
} 

void std::string input_function(std::string& s) 
{ 
    if (s == "ONE") 
    { 
    call function_one() 
    } 

    else if (s == "TWO") 
    { 
    call function_two() 
    } 

    else 
    { 
    //How do I get user to type in something else(call get_input() again)? 
    } 
} 
+0

由於您只是解析了它並將其拆分爲三個不同的字符串,所以返回'std :: string'沒有任何意義......也許您需要一個結構體。 – 2014-11-25 00:49:56

+0

對於第一個結構,struct可能是最好的選擇,也許返回一個表示命令執行成功的「bool」會適用於第二個。 – IllusiveBrian 2014-11-25 00:51:31

+0

這樣的結構與這3個元素,每個都是一個字符串。所以當我的第二個函數接受一個字符串時,我給它struct.element? – Steven 2014-11-25 00:52:12

回答

0

如果你想返回多個變量,可以考慮將它們封裝在一個結構體或類中並返回。關於輸入另一個命令,理論上你可以在你的帖子建議中使用遞歸,但這只是錯誤的,如果用戶在太多次輸入錯誤的單詞,它會使程序崩潰。相反,你可以使用一個簡單的while循環:

bool success = false; 
while(!success){ 
    /* check the input, if it's correct - process it and set success to true */ 

} 
0
struct input_result { 
    std::string command; 
    std::string first_name; 
    std::string last_name; 
}; 

有你獲取輸入函數返回上述(一input_result)。

處理輸入的函數應具有返回失敗或錯誤的方法。然後調用get_input的代碼可以調用處理代碼,注意它失敗,並返回調用get_input

您可以將兩者合併成一個名爲get_and_process的函數,該函數首先獲取,然後進行處理,如果處理失敗,則重複get。

如果您打算更改它們,您應該只帶&,否則請改爲const &

0

通常希望通過將相關數據彙集成一個struct(或class)要做到這一點:

struct whatever { 
    std::string command; 
    std::string first_name; 
    std::string last_name; 
}; 

...然後超載operator>>該類型:

std::istream &operator>>(std::istream &is, whatever &w) { 
    return is >> w.command >> w.first_name >> w.last_name; 
} 

這使得所有要在單個結構中「返回」的數據,返回的istream中返回的輸入操作的狀態,因此您可以讀取一個項目,並檢查一次操作是否成功:

std::ifstream in("myfile.txt"); 
whatever x; 

if (in >> x) 
    // input succeeded, show some of the data we read: 
    std::cout << "command: " << x.command 
       << "\tName: " << x.last_name << ", " << x.first_name << "\n"; 
else 
    std::cerr << "Input failed"; 

爲了給用戶一個機會輸入數據讀取失敗時,你通常會做這樣的事情:

while (!in >> x) 
    "Please Enter command, First name and last name:\n"; 

注意讀取數據時(尤其是數據你期望通過交互輸入用戶)你幾乎總是想檢查進去就這樣。