0

ユーザー入力に基づいて配列を埋める関数があります

このテストケースではプログラムは正常に機能しますが、必要以上に1つ多い番号をユーザーに要求します。

void fill_array(char a[], int size)
{
char next;
const char SENTIEL ='.';
int index=0;
cin >> next;


  while ((next !=SENTIEL) && (index < size))
{
   a[index] = next;
   index++;
   cin >> next;

}

cout << a[0];
cout << a[1];
cout << a[2];
cout << a[3];
cout << a[4];
cout << a[5];
cout << a[6];
cout << a[7];
cout << a[8];
cout << a[9];   
}




int main()
{
int const MAX=10;
char b[MAX];
fill_array(b,MAX);
}

これは正しい数値を返しますが、もう1つ質問する必要があります。

4

4 に答える 4

2

あなたはcin >> nextループの外側(1回)を求めています、そしてあなたは次のことにつながる時間を求めていますcin >> next size:サイズ+1回。

forループを使用する必要があります(もちろん、部外者を削除しますcin >> next)。

for (int index = 0; (next !=SENTIEL) && (index < size); index++)
{
   a[index] = next;
   cin >> next;
}
于 2013-03-26T07:20:28.433 に答える
0

文字nextを他の文字で初期化してから、前にSENTIEL読み取った文字がインクリメントされます。nextindex

char next = ' ';
const char SENTIEL ='.';
int index=0;
while ((next !=SENTIEL) && (index < size))
{
  cin >> next;
  a[index] = next;
  index++;
}
于 2013-03-26T07:23:28.410 に答える
0

変更してください:

  while ((next !=SENTIEL) && (index < size))
{
   a[index] = next;
   index++;
   cin >> next;

}

while ( ( cin >> next) && ( next !=SENTIEL) && ( index < size))
    {
       a[index] = next;
       index++;

    }

cin >> next;また、ループの外側のfristを削除し、明らかに初期化しますnext。これで問題ありません。

于 2013-03-26T07:24:27.827 に答える
0

または、次のようなこともできます。

while ((index < size) && ((cin>>next) && next!=SENTIEL) )
{
   a[index] = next;
   index++;
}

With this, If the 1st input is SENTIEL you won't enter the loop.

于 2013-03-26T07:28:21.670 に答える