Friday, June 25, 2010

Scanf problems in C

Problem 1 :
In the following C code :
#include <stdio.h>

int main ()
  char str [80];
  int i;

  printf ("Enter your family name: ");
  scanf ("%s",str);  
  printf ("Enter your age: ");
  scanf ("%d",&i);
  printf ("Mr. %s , %d years old.\n",str,i);
  printf ("Enter a hexadecimal number: ");
  scanf ("%x",&i);
  printf ("You have entered %#x (%d).\n",i,i);
  return 0;
For the family name, if I enter
a b
(i.e. 'a' followed by a 'space' followed by 'b')
all the further calls to scanf do not wait for user input and
some junk values are printed before the program terminates.
In other words, using a space character for input to scanf,
results in quite strange behaviour.
How do I fix it?

2. Problem 2 :
int main(){
char c;
printf("Enter your char\n");
printf("Enter your char\n");

In the above program the first character is read and printed
correctly, but the program doesn't wait for the next user
input. Why? How do I fix it?

Ans :
1. scanf breaks reading on any white space ... use %[^\n]s as format string to read till a newline

2. When you press enter after entering char, the \n remains in the input buffer and is used to fulfill the next read request.

Better way to get user input is to use fgets() to read in a string and then parse that string to extract the required input.

yes, its a regular expression and ^ means not

No comments:

Blog Archive