Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

"do while" loop problem 1

Status
Not open for further replies.

natwod

Programmer
Nov 21, 2002
41
0
0
US
The following is a snippet of code from a fuction I am making, but the "do while" for some reason gets stuck in an endless loop! What I want to do is read in values to the array "list" until a negative # is entered. I really need to get this fixed, if anybody can help.
THANKS!! Natwod
Code:
	double list[100];
	double temp;
	int listSize;
	listSize = 0;

	printf("Enter numbers, to stop enter -1");
	scanf("%f", &temp);
	do {
		list[listSize] = temp;
		listSize++;
		printf("Enter next number:  ");
		scanf("%f", &temp);
	} while (temp >= 0);
 
Possibilities

1) Put a fflush(stdout) after the printf. This forces the buffer to print the text. It normally prints when the buffer is full or when it hits a newline.

2) Change your while condition to

while (temp >= 0 && listSize < 100);

If the list size exceeds 100, it will start overwriting all teh other variables.
 
Hi,

I tried same code and i am not getting any endless loop.
Please let me know what exactly input u are giving ?

--Amar
 
I think it's something to do with temp being a declared
a double - but scanf being asked for float.
Double takes more space than float - so scanf for a float probably does not fill temp properly so temp is probably garbage. [which means your list will hold garbage as well].

It should work if you change temp to be a float
and then cast it as double before putting it into the list.


double list[100];
float temp;
int listSize;
listSize = 0;

printf(&quot;Enter numbers, to stop enter -1&quot;);
scanf(&quot;%f&quot;, &temp);
do {
list[listSize] = (double)temp;
listSize++;
printf(&quot;Enter next number: &quot;);
scanf(&quot;%f&quot;, &temp);
} while (temp >= 0);
 
i think guestgulkan is right about the temp being declared as float. Also the loop will have to be modified a bit(logically). At present if the first value entered is a -ve one then the loop will not be exited.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top