0

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.

4
  • you should increment the index at the end of the loop iteration. Commented Mar 26, 2013 at 7:18
  • 1
    I swear I saw this same exact question earlier... Commented Mar 26, 2013 at 7:18
  • What should happen if the user enters less than 10 numbers? Your array will contain garbage after the last entered element. Commented Mar 26, 2013 at 7:22
  • Here's the original. Please do not delete questions and re-ask them. It may lead you to a question-ban. Commented Mar 26, 2013 at 7:26

4 Answers 4

2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

value of next is garbbage. There is a chance it can be equal to SENTIEL
This change stores SENTIEL in the array and the original didn't
0

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.