0

1 つの関数で 2 つの文字列値を要求し、それらの 2 つの文字列を返す関数があります。これら2つを別の機能で別々に使用する必要があります。どうすれば両方にアクセスできますか?

プロンプト関数は次のとおりです。

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.
}

これを使用しようとしているコードは次のとおりです (これは、変更するように与えられた別のゲームから派生したものであり、元のここでは 1 つの値のみを取得します)。

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
}

助けてくれてありがとう。

4

2 に答える 2

4

これ

return column, row;

コンマ演算子を使用してを評価columnし、結果を破棄して の値を返しますrow。したがって、関数は 2 つの値を返しません。

2 つの値を返したい場合は、2 つの値を保持する構造体を記述するか、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
于 2013-06-13T21:28:36.223 に答える
0

文字列配列string[]を使用し、列をstring[0]に格納し、行をstring[1]に格納し、文字列配列を渡します

于 2013-06-13T21:30:35.693 に答える