2014-11-25 82 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"; 

注意读取数据时(尤其是数据你期望通过交互输入用户)你几乎总是想检查进去就这样。