hello everyone.

couple of days back i started learning C (with the help of internet)

i have do while loop which i can't get to work

as long as i know, when i press 'y' it should again ask temperature. but it is not doing that.

i am using Turbo C++ IDE

please check...

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>

main ()

{
int temp;
float cel;
char repeat;
clrscr();
do
{
printf ("Enter the temperature:");
scanf ("%d",temp);
cel=(5.0/9.0)*(temp-32);
printf ("%d degree F is %f degree celsius\n",temp,cel);
printf ("Do you have other temperature?");
repeat=getchar();
putchar('\n');
}
while (repeat=='y');

getch();
return 0;

}

Recommended Answers

All 6 Replies

Line 15 should be...

scanf ("%d",&temp);

This is a tough one: but this should work. You'll have to change it around, if you want to use the clrscr function. You need to break out of the nested do loop and you have to be able to exit out of the main do loop for what you desire to function properly.

#include <stdio.h>

int main(void)
{
	int temp ;
	int j ;
	float cel ;

	temp = 0 ;
	do
	{
	    printf("Enter the temperature:") ;		
	    scanf("%d", &temp) ;
	    cel = (5.0/9.0)* (temp-32);
	    printf ("%d degree F is %f degree celsius\n", temp, cel);
	    printf ("Do you have other temperature?");
	    do
	    {
		while((j = getchar()) != '\n') 
		{
		    break ;
		}
		if (j == 'n')
		    return 0 ;
	    } while (j != 'y') ;
	} while (j == 'y') ;
	 
	return 0;
}

I would recommend putting the DO loop INSIDE the while loop. You have it the other way around! :)

if you're not given an opportunity to enter 'y' for a choice, then getchar is *probably* storing '\n' in repeat. To check, try a printf

printf("\nrepeat = %d\n\n", repeat);

if so, there's different things you can do; one idea might be something like

...
scanf("%d", &temp);
while(getchar() != '\n'){}
...

HTH

nono.. its not the scanf! its the getchar. just add a fflush(stdin) statement before getchar and it will work fine

nono.. its not the scanf! its the getchar. just add a fflush(stdin) statement before getchar and it will work fine

nono.. fflush(stdin) is very wrong. See this

And yes, it's the scanf() causing the getchar() to not work as expected. Otherwise, why would you want to flush the buffer? :icon_rolleyes:

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.