繁体   English   中英

如何使一个简单的函数读取我以前的答案并给出不同的输出? (C ++)

[英]How to make simple one function read my previous answer and give different output? (c++)

所以,我是一个非常初学的编程,我正在制作一个简单的代码片段来读取用户输入和输出人员First,Middle和Lastname。

我为那些输入和输出做了3个不同的功能,但我在想,是否有可能使1个功能完成所有这些(用简单的代码语言,我还是一个非常初学者)?

它与数组和指针有关吗?

我的代码片段如下:

std::string getUserInput()
{

    std::cout << "Please write your first name: " ;
    std::string x;
    std::cin >> x;
    return x;
}

所以,我希望它能够阅读我之前的答案并给我一个不同的std :: cout输出,即“请写下你的中间名”。

谢谢你的回答!

如果我正确理解你的问题,你会想要使用函数参数:

std::string getUserInput(std::string what)
{
    std::cout << "Please write your " << what << ": " ;
    std::string x;
    std::cin >> x;
    return x;
}

int main() {
    std::string first_name = getUserInput("first name");
    std::string middle_name = getUserInput("middle name");
    ...
}

注:由于在评论中指出,这将是传递一个好主意what作为const引用。

在上面的示例中,调用函数时不必要地复制整个字符串。 你可以通过编写函数头来避免这种情况

std::string getUserInput(const std::string &what)

当你这样写时, getUserInput将处理相同的字符串对象而不是复制它。 在编写快速代码时,您应始终牢记这是C++一个属性。 我把它留在这里是为了让事情变得尽可能简单。

通过指定const ,可以防止getUserInput修改字符串。 在这种情况下,无法修改字符串,因为您使用常量字符串文字作为参数调用函数(例如"first name" )。 绝不能在CC++修改它们,否则会发生可怕的事情(即,您的应用程序可能会崩溃)。 因此,当非const引用时what您的C++编译器将阻止您编译代码。

对于这么简单的事情,你需要一个单独的功能吗?

std::cout << "Please write your first name: " ;
std::string first;
std::cin >> first;

std::cout << "Please write your middle name: " ;
std::string middle;
std::cin >> middle;

std::cout << "Please write your last name: " ;
std::string last;
std::cin >> last;

您可以将名称部分放入连接字符串或结构中,具体取决于您以后如何使用它。

您可以使用map<>循环遍历值

#include <map>
#include <string>

std::map<int, std::string> values;
std::vector<std::string> names;
values[0] = "first";
...

for (int i = 0; i < values.size(); i++)
{
    std::cout << "Please write your " << values[i] << " name" << endl;
    std::string name;
    std::cin >> name;
    names.push_back(name);
}

您也可以从用户那里获取所有三个输入。

cout << "Please write your firstname secondname lastname (with spaces): " << endl;

std::string fName,mName,lName;    
cin >> fName >> mName >> lName;

cout << "First name : " << fName << " Second name: " << mName << "Last name " << lName << endl;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM