[Homepage] | [General Lab Info] | [TA's & Tutors] | [FAQ's] | | [Homework] | [Excellent Programs] | [Exams]

> I have a question regarding using scanf with char's. I have noticed > this for a long time with C and Pascal. If I do the following line: >
> scanf("%c%f",variable1,variable2); >
> what tends to happen quite a bit is that it will stop and let me input > the char the first time but sometimes not on subsequent passes.

The problem is that %c does not skip white space as do the numerical formats such as %f and %d. This is a problem because the second time the above statement is executed, the character read is whatever whitespace terminted the float read into variable 2 (btw that should be &variable2 of course).
The following scanf can be used to skip white space and then read the next, non-white character. The * says throw away what is read, don't store it in an output variable. The [...] says read any sequence of characters matching the characters between the brackets, in this case, space, newline or tab.
scanf("%*[ \n\t]%c",&c);
Here is a short program that you can use to see it in action.

int main(void)
  int x;
  char c;

  printf("Type a number then any amount of spaces and newlines,");
  printf(" then non-white character.\n");


  scanf("%*[ \n\t]%c",&c);

  printf("c = %c\n",c);

Charlie McDowell, Professor (831) 459-4772 (w)
Computer Science Department (831) 427-2076 (h)
239 Applied Sciences (831) 459-4829 (fax)
Univ. of Calif., Santa Cruz, CA 95064 http://www.cse.ucsc.edu/~charlie
[Homepage] | [General Lab Info] | [TA's & Tutors] | [FAQ's] | | [Homework] | [Excellent Programs] | [Exams]

This page maintained by Doug Whitmore. Email regarding this site.