0

これが少しばかげた質問である場合は申し訳ありません。

これが私のコードです:

#include<iostream>
using namespace std;

int main()
{
  int columns, rows;
  char **map;

  cin>>columns;
  cin>>rows;

  /*creats array of pointers rows tall*/
  map = new char*[rows];

  /*creats array of chars columns tall*/
  for(int i=0; i<rows; i++)
    map[i] = new char[columns];

  //populate map with input
  map[0][0] = cin.get();
  for(int j=0; j<rows; j++)
    for(int i=0; i<columns; i++)
    {
      if (cin.peek() == '\n')
        cin.ignore(256, '\n');
      else
        map[j][i] = cin.get();
    }


  //DISPLAY
  cout<<endl;
  for(int j=0; j<rows; j++)
  {
    for(int i=0; i<columns; i++)
    {
      cout<<map[j][i];
    }
  }
  return 0;
}

ユーザーは次のように入力します。

7 4
#######
#S#   #
#   #E#
#######

と出力したいと思います。しかし、私のものは次のようになります:

#######
#S#    
##   #
E#####

何かご意見は?

4

3 に答える 3

2

最初の for ループ:

  //populate map with input

  for(int j=0; j<rows; j++)
  {
    cin.get();
    for(int i=0; i<columns; i++)
    {
      if (cin.peek() == '\n')
        cin.ignore(256, '\n');
      else
        map[j][i] = cin.get();
    }
  }

出力に新しい行を追加します。

  //DISPLAY
  cout<<endl;
  for(int j=0; j<rows; j++)
  {
    for(int i=0; i<columns; i++)
    {
      cout<<map[j][i];
    }
    cout << endl;
  }

入力ストリームを再度読み取る前に、必ず末尾の入力ストリームを取得してください。

于 2012-10-19T15:41:45.200 に答える
1

いくつかのこと

  • まず、ループ中map[0][0] = cin.get();に取得するため、ループの前に必要はありませんmap[0][0]

  • 次に、新しい行がある場合、ループはそれをスキップしますが、その位置のマトリックスも埋めません。代わりに次のようなものが必要です。

for(int j=0; j<rows; j++)
    for(int i=0; i<columns; i++)
    {
      while (cin.peek() == '\n')
        cin.ignore(256, '\n');
      map[j][i] = cin.get();
    }

'\ n'文字がある間は単にスキップ(無視)します。

  • 第三に、あなたの質問とは関係ありませんが。終了したら、動的に割り当てられたメモリを常に解放する必要があります(忘れた場合)

    delete [] map[i]; delete [] map;

于 2012-10-19T15:44:08.340 に答える
0

出力に改行が必要だと思います

  for(int j=0; j<rows; j++)
  {
    for(int i=0; i<columns; i++)
    {
      cout<<map[j][i];
    }
    cout << '\n';
  }
于 2012-10-19T15:27:49.323 に答える