Functions.

Here's my problem:

I'm trying to make a function that takes a number, puts it into an array and then prints it. Simple. But, I want the program to stop taking inputs and putting them into the array when someone types 'q'.

Here's what I have so far:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
void input(double ar[], int length)
{
	double a;
	for(int i = 0; i < length; i++)
	{
		cout << "Enter score " << i+1 << ":\n";
		cin >> a;
		ar[i] = a;
		int as = i+1;
		if(a == 'q')
		{
			for(; as < length - 1; as ++)
			{
				ar[as] = '/0';
			}
			break;
				
		}
	}
}
line 9 as has never been declared? is this a global variable? If you are trying to track how many values were actually entered consider in your main function doing this.

1
2
int numread=0;
numread = int input(arrayname, size);

Obviously you would need to change the input return type and actually return a value so numread can acquire it.

@ line 10 you are comparing an int value to a character constant q. This is comparing the value entered with he ASCII code if I remember correctly.

You would be better off checking to see if input succeeded for cin or using a second prompt
1
2
3
4
5
6
7
char ch;
cout << "Continue?(q to quit):";
cin.get(ch);
if (ch == 'q')
{
break;
}


Something along those lines should work.
Last edited on
That doesn't make too much sense.

You're reading in a double, and then comparing that double to a char... What you should probably do is read a string, check if that string starts with a q, and if not attempt to convert it to a double and put it into the array. If it does though, just break.

And you should really use a vector instead of an array, then you'd you save yourself the question "what do I do with the leftover spaces?" - cause you wouldn't have any.
*Sigh*

Well, I need to look closer into what I am declaring with my variables.

Thank you for your help!
Topic archived. No new replies allowed.