Two basic questions on this Array example: on C++


This code is a basic entry Array, and is from a tutorial and doesn't quite work properly because the "-1" when typed is pointless and the Array still prints if you type a letter and press enter when it is supposed to only print when you type, "-1". Do you know why it is not working and why did the teacher chose "-1"? Is there a reason for this, like leaving it to be later connected to a button option. Because I think I've seen "-1" in other tutorial examples. So I'm wondering why that and why it is not working properly.

const int CAP = 5;

int main()
{
string col[CAP];
int i = 0;
int NUMElements = 0;
string input;

cout << "Please type in the colours you want (-1 to stop):";
cin >> input;
while ((input != "-1") && (i < CAP))
{
NUMElements++;
col[i] = input;
i++;
cin >> input;
}
for (int j = 0; j < NUMElements; j++)
{
cout << "Colour #" << (j + 1) << " " << col[j] << endl;
}

return 0;
}
Hello logana,

PLEASE ALWAYS USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post.
http://www.cplusplus.com/articles/jEywvCM9/
http://www.cplusplus.com/articles/z13hAqkS/
Hint: You can edit your post, highlight your code and press the <> formatting button.
You can use the preview button at the bottom to see how it looks.

Do not be afraid to use blank lines to break up your code. It makes it easier to read.

I a not sure why it did not work for you because when I tried it the program worked except that I had to enter six colours before the while loop ended.

The use of -1 to end the loop is because -1 is not likely to be a colour that you would enter. It could just as easily be -99 or end. Anything that would not be a normal entry.

Hope that helps,

Andy
Hello logana,

After working with your program I determined the while loop did not work well. A "do while" loop works better. The code inside the loop works, but it is in the wrong order. Nothing needs removed just added. Hint following the "cin" you will need to check for "-1" and break out of the loop if it is.

The "while" condition has one to many checks. You may find this a good place to start:
http://www.cplusplus.com/doc/tutorial/control/#dowhile or search "do while loops".

I will give you a chance to work on the program to see what you come up with first.

Hope that helps,

Andy

Edit: Hint when you change your program the first "cin" will not be necessary.
Last edited on
Thanks Andy,I will take that all on board. I think the "-1" is kinda pointless, easier to remover the whole thing really and simply create a future version that dissects what it is trying to-do.

I think what I am grabbling with; is there a better way to execute the code with the option of entering a key board selection. I will look at the order and then move on from it.

I will do the Tags in future. I appreciate the help thank you!
Topic archived. No new replies allowed.