从C++输入中收集数据时,是否有更有效的方法可以处理变量
Is there a more efficient way I could handle variables when collecting data from input in C++?
我正在收集名字和姓氏,以便收集一个人的全名。
我知道我可以通过以下方式做到这一点:
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中显示的内容。的回答。
相关文章:
- 在C++中初始化向量映射的最有效方法
- 将此布尔值传递给此函数的最有效方法是什么?
- 比较C++变量的最有效方法
- 在 c++ 中解决段树以外的范围查询的有效方法是什么?
- 存储变量的更有效方法是什么?
- 确保套装新鲜度的有效方法
- 当映射包含字符串向量作为值时,从值中获取键的有效方法
- 映射唯一值和重复值的有效方法.可以访问键或值的位置
- 在C++事务之间存储大量字符数据的有效方法
- 在unordered_multimap中精确迭代一次每个键的有效方法
- 一种将 Dart 中的字节数据转换为 C++ 中的无符号字符*的有效方法?
- 检查两个向量是否并行的最有效方法
- 从浮点数中删除小数部分但保留类型的有效方法
- 传递非泛型函数的最有效方法是什么?
- 按升序打印矢量的所有元素直到它为空而没有重复项的最有效方法是什么?
- 创建字符串数组的有效方法
- 返回一个引用C++中另一个类对象的对象的有效方法
- C++去除前x个元素的有效方法,在不改变向量大小的情况下将第x+1个元素推到第一个
- 将一种数据类型的向量复制到同一数据类型的结构向量中的有效方法是什么
- 从std::map值中获取密钥的有效方法