如何从函数中检索两个istream值

How to retrieve two istream values from a function

本文关键字:两个 istream 函数 检索      更新时间:2023-10-16

我有一个函数,它提示在一个函数中输入两个字符串值,然后返回这两个字符串。我需要在不同的函数中分别使用这两个。我如何访问两者?

下面是提示函数:

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],并将字符串数组传递给