如何从函数中检索两个istream值
How to retrieve two istream values from a function
我有一个函数,它提示在一个函数中输入两个字符串值,然后返回这两个字符串。我需要在不同的函数中分别使用这两个。我如何访问两者?
下面是提示函数:
string othello::get_user_move( ) const
{
string column;
string row;
display_message("Enter Column: ");
getline(cin, column); // Take value one.
display_message("Enter Row: ");
getline(cin, row); //Take value two.
return column, row; //return both values.
}
这是试图使用它的代码(它是从另一个游戏中衍生出来的,我们可以修改,这里的原始代码只抓取一个值):
void othello::make_human_move( )
{
string move;
move = get_user_move( ); // Only takes the second value inputted.
while (!is_legal(move)) // While loop to check if the combined
// column,row space is legal.
{
display_message("Illegal move.n");
move = get_user_move( );
}
make_move(move); // The two values should go into another function make_move
}
非常感谢大家的帮助。
This
return column, row;
使用逗号操作符,计算column
,丢弃结果,并返回row
的值。所以你的函数不会返回两个值。
如果你想返回两个值,你可以写一个包含两个值的结构体,或者使用std::pair<std::string, std::string>
#include <utility> // for std::pair, std::make_pair
std::pair<string, string> othello::get_user_move( ) const
{
...
return std::make_pair(column, row);
}
然后std::pair<std::string, std::string> col_row = get_user_move();
std::cout << col_row.first << "n"; // prints column
std::cout << col_row.second << "n"; // prints row
使用字符串数组string[],将列存储为string[0],将行存储为string[1],并将字符串数组传递给
相关文章:
- 如何在C++中从两个单独的for循环中添加两个数组
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 当在同一名称空间中有两个具有相同签名的函数时,会发生什么
- 如何返回一个类的两个对象相加的结果
- 如何在C++中将一个无符号的 int 转换为两个无符号的短裤?
- 如何将两个不同矢量的同一位置的两个元素组合在一起
- 两个字符串在 c++ 中不相等
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 两个文件使用彼此的功能-如何解决
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 如何确保在使用基于布尔值的两个方法之一调用方法时避免分支预测错误
- 停止cmake target_link_libraries将插件中静态库的两个对象文件链接到静态库本身
- 将fold表达式与std::一起用于两个元组
- 如何在C++中比较两个char数组
- 给定两个偶数,求出它们之间所有偶数的平方和
- 比较两个大小不等的映射c++
- c++读取txt文件并复制到两个类istream::peek()中
- c++:Istream 将.txt文件中的每个换行符计为两个
- 如何比较两个 std::istream 引用
- 如何从函数中检索两个istream值