user2001875
user2001875

Reputation:

C++ filling array issue

I have a function that fills an array based on user input

The program works fine in this test case but it asks the user for one more number than needed.

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);
}

this returns the correct numbers but it has one more to ask.

Upvotes: 0

Views: 437

Answers (4)

4pie0
4pie0

Reputation: 29724

please change:

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

}

to

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

    }

also delete frist cin >> next; outside the loop, and obviously initialize next, and it's OK

Upvotes: 0

Suvarna Pattayil
Suvarna Pattayil

Reputation: 5239

Alternatively you can do something like this,

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.

Upvotes: 0

999k
999k

Reputation: 6565

Intialise character next with some other character than SENTIEL and then read next before index is incremented.

char next = ' ';
const char SENTIEL ='.';
int index=0;
while ((next !=SENTIEL) && (index < size))
{
  cin >> next;
  a[index] = next;
  index++;
}

Upvotes: 0

Shoe
Shoe

Reputation: 76240

You are asking for cin >> next outside the loop (1 time) then you are asking for cin >> next size time which leads to: size + 1 times.

You should use a for loop (and of course remove the outsider cin >> next):

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

Upvotes: 2

Related Questions