gpt4 book ai didi

c++ - 我需要对 C++ 有一些了解;用字符串和整数重载

转载 作者:行者123 更新时间:2023-11-28 01:53:41 24 4
gpt4 key购买 nike

我们在类里面做了这个练习:

Using default arguments, write a function that ask the user for a number and returns that number. The function should accept a string prompt from the calling code. If the caller does not supply a string for the prompt, the function should use a generic prompt. Next, using function overloading, write a function that achieves the same results.

措辞令人困惑,但我知道我需要两个方法,一个 int 和一个 string,来重载。

但在与我的老师交谈后,他解释说,使用该程序,用户应该能够输入 int 5 或字符串“five”,并且该程序应该能够确定它是 int 还是 string 并输出

我查阅了这个练习,发现有几个“解决方案”,但没有一个在我老师的参数范围内有效。

是否可以像我老师解释的那样创建一个程序?

如果没有,是否有人对说明有任何其他解释?

最佳答案

老师的话是这样翻译的:

#include <string>
#include <iostream>
#include <stdexcept>

/**
* Prompts the user for an integer input on standard input, and
* returns it. The prompt text is #prompt_text, or "Enter input please"
* if not given.
*
* @throws std::runtime_error if input is not an integer
*/
int promptForInput(const std::string& prompt_text = "Enter input please")
{
std::cout << prompt_text << ": " << std::flush;

int result;
if (std::cin >> result)
return result;
else
throw std::runtime_error("Could not understand your input");
}

int main()
{
const int x = promptForInput();
std::cout << "You entered: " << x << std::endl;

const int y = promptForInput("Gimme intz lol");
std::cout << "You entered: " << y << std::endl;
}

使用重载而不是默认参数,函数是这样的:

/**
* Prompts the user for an integer input on standard input, and
* returns it. The prompt text is #prompt_text.
*
* @throws std::runtime_error if input is not an integer
*/
int promptForInput(const std::string& prompt_text)
{
std::cout << prompt_text << ": " << std::flush;

int result;
if (std::cin >> result)
return result;
else
throw std::runtime_error("Could not understand your input");
}

/**
* Prompts the user for an integer input on standard input, and
* returns it. The prompt text is "Enter input please".
*
* @throws std::runtime_error if input is not an integer
*/
int promptForInput()
{
return promptForInput("Enter input please");
}

在这两种情况下,这个程序的输出都是这样的:

[tomalak@andromeda ~]$ ./test2
Enter input please: 4
You entered: 4
Gimme intz lol: 62
You entered: 62

如果您输入一个非整数,您将得到一个非描述性的过程错误:

[tomalak@andromeda ~]$ ./test2
Enter input please: lol
terminate called after throwing an instance of 'std::runtime_error'
what(): Could not understand your input
Aborted (core dumped)

(注意,我建议在 main 中使用 try/catch 情况,但我不会被打扰。)


But after talking with my teacher, he explained that with the program a user should be able to enter and int 5 or a string "five", and the program should be able to determine if it is an int or string and output it.

我无法想象这是对的;这似乎毫无意义,并且与引用的作业无关。我相信你误解了这段对话。

关于c++ - 我需要对 C++ 有一些了解;用字符串和整数重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41987015/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com