Need your help in this code too..
this is the program to convert any entered number into its hexadecimal equivalent but the problem is that same result is printed for any number...:'( :'(

int main (void)
{
	int n;
	printf("Enter Number :");
	scanf("%d", n);
	printf("Hexadecimal Equivalent %x", n);
	getch();
	return 0;

}

>printf("Enter Number :");
You should call fflush ( stdout ) after this. The stream buffer is only guaranteed to be flushed when it's full (which you can't portably determine), when a newline is printed (which you aren't doing for this prompt), or when fflush is called. If stdout isn't flushed before the scanf call, your user may not see the prompt.

You also need to include stdio.h. Your code presently exhibits undefined behavior.

>scanf("%d", n);
scanf takes a pointer to int so that it can store the value in your variable. Because n isn't already a pointer, you need to pass the address of n. You should also be checking the return value of scanf in case the user can't type or follow instructions.

>getch();
You need to include conio.h, but getchar is better because it's standard while getch is not.

Here's a better example:"

#include <stdio.h>

int main ( void )
{
  int n;

  printf ( "Enter Number: " );
  fflush ( stdout );
	
  if ( scanf ( "%d", &n ) == 1 )
    printf ( "Hexadecimal Equivalent %x\n", n );

  while ( getchar() != '\n' )
    ;
  getchar();

  return 0;
}

> scanf("%d", n);
Are you using gcc?
Have you considered gcc -W -Wall prog.c You forgot the &, which the above compiler/warning options would tell you.

Yes salem you r rite........
Im now wondering that how i forgot to put &:-O

While compiling the following

#include <stdio.h>
int main ( void )
{
int n;
printf ( "Enter Number: " );
fflush ( stdout );
if ( scanf ( "%d", &n ) == 1 )
printf ( "Hexadecimal Equivalent %x\n", n );
while ( getchar() != '\n' )
;
getchar();
return 0;
}

compiler shows a warning..."code has no effect"

Edited 3 Years Ago by happygeek: fixed formatting

>Borland C++
That makes sense. Borland likes to complain about unused results. You can safely ignore the warning (because getchar really does something here), or you can cast the result to void to silence the warning:

(void)getchar();

> The problem is solved by replacing getchar(); with getch();
No, that makes your program unportable for no good reason.

>The problem is solved by replacing getchar(); with getch();
Fine. Use getch then. It's not like I went out of my way to point out that getch is non-portable and offer a perfectly valid alternative. Oh wait, I did. I guess some people just insist on refusing to learn and doing stupid things. Next time I won't waste my time being so helpful.

>Next time I won't waste my time being so helpful.


I have done anythin wrong??
thanks for solving the program by the way...:icon_biggrin:

This question has already been answered. Start a new discussion instead.