0

I've bumped into a problem. I'm trying to store user entered values into an array until they enter -1 by using a do-while loop. Here's a sample of my code:

int j=0; do{ cin >> nodes[j]; j++; } while (nodes[j] != -1); 

Can someone tell me why this doesn't work and what a better approach would be? Thanks!

1
  • 1
    Isnt j` already incremented when the comparison nodes[j] != -1 is made? Commented Apr 3, 2014 at 1:48

6 Answers 6

2

It doesn't work because you've increment end the index (j) after receiving input and before reading input. You could instead compare nodes[j-1] == -1

Also important, you might overrun your array if you don't put in a maximum number of elements.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! I have a max number of elements for that array earlier up in my function so no worries! T
You need to abort the loop when that max is hit, even if -1 hasn't been provided... Easy to do that, by terminating on -1 || j == max
2

Isn't j already incremented when the comparison nodes[j] != -1 is made?

Also, I presume, that we do not want to store the sentinel value -1 into the array.

for( int j = 0; j != NodeMax; ++j) { int tmp = 0; cin >> tmp; if( tmp == -1 ) { break; } node[ j ] = tmp; } 

Comments

1

As @Arun mentioned, j is already increased when nodes[j] != -1 is checked.

Modify as follows:

do { cin >> nodes[j]; } while (nodes[j++] != -1); 

Comments

1

The statement while (nodes[j] != -1); will never be true because you are incrementing j and moving on the the next index before checking the value. A better approach would be this:

do{ cin >> nodes[j]; } while (j < SIZE && nodes[j++] != -1); 

1 Comment

Now j is incremented twice in one loop!
0

nodes[j] isn't the nodes[j] you enter since it has been ++, try this: while(cin>>node[j++]);

Comments

0

You are incrementing j before node[j]!=-1 check. Either do this

int j=-1; do{ j++; cin >> nodes[j]; } while (nodes[j] != -1); 

or

int j=0; do{ cin >> nodes[j]; } while (nodes[j++] != -1); 

or

int j=0; while(cin>>nodes[j] && nodes[j]!=-1) { j++; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.