从C++输入中收集数据时,是否有更有效的方法可以处理变量

Is there a more efficient way I could handle variables when collecting data from input in C++?

本文关键字:有效 方法 变量 处理 是否 输入 C++ 数据      更新时间:2023-10-16

我正在收集名字和姓氏,以便收集一个人的全名。

我知道我可以通过以下方式做到这一点:

    string firstname;
    string lastname;
    string fullname;
    cout << "Users firstname ? "; cin >> firstname;
    cout << "Users last name ? "; cin >> lastname;
    fullname = firstname + ' ' + lastname;

在python中,我可以:

first_name = input("What is your first name?")

这样做很好,因为它在一行中提供了变量的初始化和值的赋值。

有没有办法在C++中使用相同的设计来减少代码中的冗余?

您可以实现input函数的C++版本并使用它。 例如:

#include <iostream>
#include <exception>
#include <string>
std::string input() {
    std::string line;
    if(getline(std::cin, line))
        return line;
    throw std::runtime_error(std::cin.eof() ? "end of input" : "input error");
}
std::string input(char const* prompt) {
    (std::cout << prompt).flush();
    return input();
}
int main() {
    auto firstname = input("Enter first name? ");
    auto lastname = input("Enter last name? ");
    auto fullname = firstname + ' ' + lastname;
    std::cout << "Hello " << fullname << 'n';
}

嘿,我认为您可以轻松摆脱其中一个变量。

#include <iostream>
#include <string>
int main()
{
std::string lastname;
std::string fullname;
std::cout << "Users firstname ? "; std::cin >> fullname;
std::cout << "Users last name ? "; std::cin >> lastname;
fullname += ' ' + lastname;
std::cout << "Full name: " << fullname << std::endl;
return 0;

}

您想要使用迭代器的第二种方式是更多您正在寻找的内容。

#include <iostream>
#include <string>
#include <iterator>
int main()
{
    std::cout << "Users firstname ? ";
    std::istream_iterator<std::string> it(std::cin);
    std::string fullName;
    std::cout << "Users lastname ? ";
    fullName += *it;
    ++it;
    fullName += ' ' + *it;
    std::cout << "Full Name: " << fullName << "n";
    return 0;
}

我个人认为第一种方法更容易阅读和遵循。

reddit上有一篇有趣的帖子,用你展示的例子涵盖了这个主题。

目前,C++没有实现相同目标的标准方法,但是该帖子的作者提供了一个仅标题库(这意味着您可以将代码复制粘贴到您的文件/项目中的文件或简单地包含依赖项)这样做,例如:

int age = read<int>("Please enter your age: ");
cout << "You are " << age << " years old.n";
<小时 />

如果你对应用外部依赖不感兴趣,你必须坚持使用标准解决方案,即你在问题中展示的内容和Eddie C中显示的内容。的回答。