返回两个用户输入值的函数
A function to return two user input values
我希望能够有一个函数,它只需从用户那里获得两个输入值,并返回这些值供主函数使用。
我希望值a和b只存在于getvals函数中,并作为x和y传递到主函数中。
我想我可能在这里做得不对,因为我已经搜索了很多,找不到任何类似的方法来做这件事,但如果有任何帮助,我将不胜感激。
#include <iostream>
using namespace std;
int x = 100;
int y = 42;
int result1;
int result2;
int a;
int b;
int getvals(int,int)
{
cout << "input value a ";
cin >> a;
cout << "input value b ";
cin >> b;
return a,b;
}
int main()
{
getvals(x,y);
result1 = x + y;
cout << "nn";
cout << " x + y = " << result1;
return 0;
}
一个函数只能返回一个值。幸运的是,您可以将两个值包装在一个结构或类中,并将其作为一个对象返回。这正是std::pair
的设计初衷。
std::pair<int,int> getvals()
{
std::pair<int,int> p;
cout << "input value a ";
cin >> p.first;
cout << "input value b ";
cin >> p.second;
return p;
}
int main()
{
std::pair<int,int> p = getvals();
int result1 = p.first + p.second;
...
}
C++11引入了更通用的std::tuple
,它允许任意数量的元素。
std::tuple<int,int> getvals()
{
int a,b;
cout << "input value a ";
cin >> a;
cout << "input value b ";
cin >> b;
return std::make_tuple(a,b);
}
int main()
{
int x,y;
std::tie(x,y) = getvals();
...
}
对a
和b
使用引用。
void getvals(int &a, int &b)
{
cout << "input value a ";
cin >> a;
cout << "input value b ";
cin >> b;
}
这声明getvals()
采用两个引用参数。对对象引用的修改会修改传递给函数调用的对象。
在没有引用的情况下,参数是通过值传递的,该值会创建传递给函数的对象的副本。然后,对函数中的参数所做的修改只会影响副本。
或者,您可以使用std::pair<int, int>
从函数中返回两个整数值(然后不需要out参数)。您可以手动将first
和second
成员解包到变量x
和y
中,也可以实现一个助手类来完成此操作。例如:
std::pair<int, int> getvals () {
std::pair<int, int> p;
std::cin >> p.first;
std::cin >> p.second;
return p;
}
template <typename T, typename U>
struct std_pair_receiver {
T &first;
U &second;
std_pair_receiver (T &a, U &b) : first(a), second(b) {}
std::pair<T, U> operator = (std::pair<T, U> p) {
first = p.first;
second = p.second;
return p;
}
};
template <typename T, typename U>
std_pair_receiver<T, U> receive_pair (T &a, U &b) {
return std_pair_receiver<T, U>(a, b);
}
int main () {
int x, y;
receive_pair(x, y) = getvals();
//...
}
如果您有可用的C++11,您可以使用更通用的tuple
和tie
帮助程序以更干净的方式进行类似的操作。本杰明·林德利的回答说明了这一点。
您似乎已经完成了通过参数返回的一半。你所需要改变的是:
void getvals( int& a, int& b )
{
cout << "input value a ";
cin >> a;
cout << "input value b ";
cin >> b;
}
注意参数名称之前的&
,意思是通过引用传递。这意味着当它们在函数中发生变化时,它们也会在调用者中发生变化。不需要return
。
通过引用将值传递给函数,并更改其定义以返回void。类似这样的东西:
void getvals(int &a,int &b)
{
cout << "input value a ";
cin >> a;
cout << "input value b ";
cin >> b;
return;
}
函数只能返回一个值。这个东西可以是一个数组,在某些情况下是合适的。
通常情况下,正确的事情(TM)是在调用函数中声明变量。将对这些变量的引用传递给应该设置这些变量的函数。使用函数中传递的引用可以在调用程序中设置变量,就像返回变量一样。如果采用这种方法,那么让函数返回成功/失败并通过引用处理所有数据输出可能是个好主意。
祝你好运。我在帮你拉。我们都在一起。
- 通过 ssh 发送参数.是否有非阻塞输入函数?
- 将int输入函数,将int输入开关,然后更改int的值
- 不能将类中的输入函数与带参数的函数分开
- "cin.get"停止了另一个输入函数,如"cin"..C++
- 模板函数中的错误以获取来自C 输入函数的参数类型
- 两个输入函数的 T(n) 运行时
- 指针在输入函数时丢失值
- (C++)对文件输入函数的递归调用
- 在 Linux 上使用 C 中的输入函数,无需按回车键
- 我在输入函数上做错了什么
- 简单的c++输入函数
- 如何确定未格式化输入函数读取的字符数
- 当我超过第一个 getline() 的输入中的数组大小时,第二个 getline 或其他输入函数不起作用
- 将文件读取到向量中,我的输入函数有什么问题?
- Pthread_create似乎清空了传递给输入函数的参数
- 将具有可变参数的输入函数转换为成员函数
- 直接输入函数
- 如何:捕获输入函数异常的可变包装函数
- 返回命令输入函数
- 是否可以在if语句中使用_getch()或cin或任何输入函数?