How do i make input stop if invalid key entered

Im trying to make the input stop but it ends up showing the whole thing
the problem is in the Fill_array() function

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
  #include <iostream>

/* 
6. Write a program that uses the following functions:
Fill_array() takes as arguments the name of an array of double values and an array
size. It prompts the user to enter double values to be entered in the array. It ceases taking
input when the array is full or when the user enters non-numeric input, and it
returns the actual number of entries.
Show_array() takes as arguments the name of an array of double values and an array
size and displays the contents of the array.
Reverse_array() takes as arguments the name of an array of double values and an
array size and reverses the order of the values stored in the array.
The program should use these functions to fill an array, show the array, reverse the array,
show the array, reverse all but the first and last elements of the array, and then show the
array 
*/

double Fill_array(double *array, int max, int *counter);
void Show_array();
double Reverse_array();

const int Max = 50;

int main(int argc, char** argv) 
{
	int counter = 0;
	double *array;
	array = new double[Max];
	*array = Fill_array(array, Max, &counter);
	//Show_array(array, Max);
	std::cout << std::endl <<counter;
	return 0;
}

double Fill_array(double *array, int Max, int *counter)
{
	std::cout << "Enter any non numeric key to stop.\n";
	std::cout << ++*counter <<": ";
	while((std::cin >> array[*counter]) || (*counter < Max)) 
	{          //how do i stop the input if input entered is non numeric
		std::cout << *counter + 1 <<": ";
		++*counter;
	}
}

//void Show_array(double * array, int Max)

For now you are looping while at least one of the conditions is true. You need to loop while both conditions are true
You will need an input validation. Something with
1
2
3
4
5
6
7
8
9
if(parameters to check if the input is numeric or not)
{
     cout << "Invalid Input.\n";
     //force abort
}
else
{
     //continue entering numerical input until max is reached or non numeric is entered
}
fixed it
1
2
3
4
5
6
7
8
9
10
11
12
13
void Fill_array(double *array, int Max, int *counter)
{
	std::cout << "Enter any non numeric key to stop.\n";
	while(*counter < Max)
	{
		std::cout << *counter + 1 <<": ";
		std::cin >> array[*counter];
		if(!std::cin)
		break;
		else
		++*counter;
	}
}
Last edited on
Topic archived. No new replies allowed.