Jump to content
  • Advertisement
Sign in to follow this  
Mkk

character value

This topic is 4863 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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.

Share this post


Link to post
Share on other sites
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)

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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

}

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!