I am making a function in a class where it asks the user to enter in numbers and to enter in a -1 when you are done with the list. I used the code below. The problem is that when they put a -1 to tell the program to stop collecting numbers, it stores -1 as a number in the array. How can I make it so -1 isnt stored? Thanks.
1 2 3 4 5 6
void Numbers() {
for (int i = 0; i < n; i++) {
cin >> a[i];
if (a[i] < 0) { break; }
}
}
Depending on what your situation is, it might even be desirable to keep the negative number, as a way to mark the end of the input.
For instance:
1 2 3 4 5 6 7 8 9 10 11 12 13
int array[101]; // Plenty of elements
std::cout << "Enter up to 100 elements, and enter -1 when you are done: ";
for (int i = 0; i < 100; ++i)
{
std::cin >> array[i];
if (array[i] == -1)
break;
}
array[100] = -1; // If the user entered 100 elements, this will mark the end of the input
std::cout << "Here's what you entered:\n";
for (int i = 0; array[i] != -1; ++i) // Use the -1 to know when to stop
std::cout << array[i] << '\n';
Enter 5 numbers:
Number 1: 3
Number 2: 7
Number 3: 8
Number 4: -1
Number 5: -12
Numbers entered:
3,7,8,-1,-12
I have a different
example using
EOF end-of-file
character to stop when you are
done;
Enter 10 numbers (ctrl+D to quit)
Enter number #1 :1
Enter number #2 :4
Enter number #3 :-1
Enter number #4 :5
Enter number #5 :-4
Enter number #6 :30
Enter number #7 :9
Enter number #8 :^D <-- EOF (ctrl+D Mac OS X)
Numbers entered:
1 4 -1 5 -4 30 9
//EnterNumbers.cpp
//##
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int EnterNumbers(int array[],intconst SIZE);
void PrintArray(int array[],intconst INDEX);
int main(){
intconst SIZE=10;
int index;
int setNumbers[SIZE]={};
index=EnterNumbers(setNumbers,SIZE);
PrintArray(setNumbers,index);
return 0; //indicates success
}//end main
int EnterNumbers(int array[],intconst SIZE){
cout<<"Enter "<<SIZE<<" numbers (ctrl+D to quit)"<<endl;
for(int i=0;i<SIZE;i++){
cout<<"Enter number #"<<i+1<<" :";
cin>>array[i];
if(cin.eof()){
return i;
}//end if
}//end for
return SIZE;
}//end function EnterNumbers
void PrintArray(int array[],intconst INDEX){
cout<<endl;
for(int i=0;i<INDEX;i++){
cout<<array[i]<<((i+1)%10==0?'\n':' ');
}//end for
cout<<endl;
}//end function PrintArray