character value

Started by
3 comments, last by Mkk 18 years, 9 months ago
What happends when I give character rather than double value when asked?

#include <iostream>
using namespace std;

int fill_array(double ar[], int limit);

int main()
{
	double ar[7] = {0};

	fill_array(ar, 7);

	system("PAUSE");
	return 0;
}

int fill_array(double ar[], int limit)
{
	double temp;
	for (int i = 0; i < limit; i++)
	{
		cout << "Give number " << i + 1 << ": ";
		cin >> temp;
		
		ar = temp;

		cout << ar;
	}

	return i;
}
It fills whole array with the number last given but I don´t really understand why, so plz help.
Advertisement
could it be that the loop just goes too fast?
maybe you should do a small sleep between every cycle.
maybe it just runs all the loop while you still have
your finger on the key.
(just a guess)
Now get down on your hands and knees and start repeating "Open Source Good, M$ Evil", smacking your head against the pavement after each repetition. Once you have completed your training you may change your first name to GNU/, to show that you are free from the slavery of the closed source world. -Michalson
Try replacing cin >> temp with this:

while(!(cin >> temp)){cin.clear();while(cin.get() != '\n'){}}


if cin can't store the input it "fails" and the input buffer needs to be cleared. In the failed state cin will not except any new input.
Standard input requires a newline after your input, so the loop can't go to fast.
But that newline is the problem, it's still in the inputstream, after reading the number and that sets the stream in "bad"-mode, when it tries in the next iteration to read a new number.
To avoid this you have to clear the stream for the next value.
Try this (I hope it works):
#include <iostream>using namespace std;int fill_array(double ar[], int limit);int main(){	double ar[7] = {0};	fill_array(ar, 7);	system("PAUSE");	return 0;}int fill_array(double ar[], int limit){	double temp;	for (int i = 0; i < limit; i++)	{		cout << "Give number " << i + 1 << ": ";		cin >> temp;		cin.ignore( ); 		ar = temp;		cout << ar;	}	return 1; // i exists only in the for loop-scope}
Ok, got it working. Thanks!

This topic is closed to new replies.

Advertisement