Can't scanf char

This is a discussion on Can't scanf char within the C Programming forums, part of the General Programming Boards category; Hello I have i question. why i can't scanf character when i open file e.g. Code: if ( ( fp ...

  1. #1
    Registered User
    Join Date
    Nov 2011
    Posts
    58

    Can't scanf char

    Hello I have i question. why i can't scanf character when i open file e.g.
    Code:
    if ( ( fp = fopen( "list.txt", "w" ) ) == NULL )
                             {
                                  printf("No such file. \n");
                                  system ("pause");
                             }
                             else
                             {
                                   printf("Enter character \n");
                                   scanf("%c", &ch);
                             }
    fclose(fp);
    Program just skips this and don't let enter character.
    Last edited by krakatao; 04-11-2012 at 08:27 AM.

  2. #2
    Registered User claudiu's Avatar
    Join Date
    Feb 2010
    Location
    London, United Kingdom
    Posts
    2,094
    ?? Is there a character in that file to read, to begin with?

    EDIT: NM, I thought you were doing a fscanf.
    Last edited by claudiu; 04-11-2012 at 08:33 AM.
    1. Get rid of gets(). Never ever ever use it again. Replace it with fgets() and use that instead.
    2. Get rid of void main and replace it with int main(void) and return 0 at the end of the function.
    3. Get rid of conio.h and other antiquated DOS crap headers.
    4. Don't cast the return value of malloc, even if you always always always make sure that stdlib.h is included.

  3. #3
    Registered User
    Join Date
    May 2010
    Posts
    2,713
    This is probably being caused by input prior to the code you posted. You probably have a end of line character left in the input buffer by a previous read. Try adding a space before your %c in your format specifier.
    Code:
    scanf(" %c,&yourVariableName);
    Also note that scanf() is reading from the console not your file.

    Jim

  4. #4
    Registered User
    Join Date
    Nov 2011
    Posts
    58
    You're right. Thank you very much

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. scanf , char, newline, space
    By Harry Reve in forum C Programming
    Replies: 1
    Last Post: 09-11-2011, 06:49 AM
  2. scanf/printf char troubles
    By XantuVolo in forum C Programming
    Replies: 2
    Last Post: 04-10-2011, 01:51 PM
  3. Issue with scanf and char
    By Covalent in forum C Programming
    Replies: 6
    Last Post: 11-02-2008, 11:06 PM
  4. Reading in char for float with scanf
    By ramparts in forum C Programming
    Replies: 3
    Last Post: 11-05-2006, 12:05 AM
  5. char pointer working in scanf but not in cin.
    By sawer in forum C++ Programming
    Replies: 14
    Last Post: 06-15-2006, 02:15 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21