Thread: scanf vs gets

  1. #1
    Registered User
    Join Date
    Dec 2005
    Posts
    167

    scanf vs gets

    Code:
    #include<stdio.h>
    #include<string.h>
    
    int main()
    {
            char a[100],*p;
            int ch;
            printf("a: ");
            scanf("%s",a); //gets(a)
            printf("ch: ");
            ch=getc(stdin);
            p=strchr(a,ch);
            puts(p);
            return 0;
    }
    if i run this prog i get seg fault.... but if i use gets instead of scanf i don't get any problem.
    how can i solve this ?

  2. #2
    Registered User
    Join Date
    Aug 2005
    Posts
    1,267
    the program does not crash because of scanf(). It crashes because it uses a potentially NULL pointer -- p -- in the puts line. strchr() will return NULL when ch is not found in array a.

  3. #3
    The Richness... Richie T's Avatar
    Join Date
    Jan 2006
    Location
    Ireland
    Posts
    469
    you shouldnt use either - you are getting a segmentation fault because when you use scanf, the newline character '\n' is stored in the input buffer - when you call getc, it sees the newline and thinks that you have hit enter. this causes problems with the next part of your code. also, gets doesn't store the newline.

    however both scanf and gets are not good choices to use because they allow a user to enter as many characters as they like - this can cause a buffer overflow in your array/string. this is very common grievance with c and resultantly there is a way around it: fgets.

    you can stop from skipping over the call to getc by using a scanf instead

    it is here though that i notice that you are trying to retrieve an integer from a string - why?

    i'm not sure of what your code is aiming to do, but you should use an if statement when using strchr like the following

    Code:
            if ((p=strchr(a,ch)) != NULL)
            puts(p);
    with any luck, that will shed some light on your problem, it stops the segmentation error in my compiler. here is a link about fgets - you should consider replacing scanf and gets with it, also uses strchr

    http://faq.cprogramming.com/cgi-bin/...&id=1043284385
    No No's:
    fflush (stdin); gets (); void main ();


    Goodies:
    Example of fgets (); The FAQ, C/C++ Reference


    My Gear:
    OS - Windows XP
    IDE - MS Visual C++ 2008 Express Edition


    ASCII stupid question, get a stupid ANSI

  4. #4
    Registered User
    Join Date
    Dec 2005
    Posts
    167
    Code:
    #include<stdio.h>
    #include<string.h>
    
    int main()
    {
            char a[100],*p;
            int ch;
            printf("a: ");
            scanf("%s",a);
            printf("ch: ");
            while((ch=getc(stdin))=='\n');
            p=strchr(a,ch);
            puts(p);
            return 0;
    }
    but isn't there somekind of flash buffer function ?

  5. #5
    The Richness... Richie T's Avatar
    Join Date
    Jan 2006
    Location
    Ireland
    Posts
    469
    there are ways to flush the buffer, but the reason i suggested fgets is that you should use a better function than that which you were using. if you read the faq on it, you would see that the newline character is stored in the string and they describe a way of removing it from your string - this takes the problem away from flushing the input buffer.

    flushing the input buffer is a hottly debated topic in this forum, try a forum search if you wish to proceed with using the unsafe functions, but i suppose its not a bad thing to be familiar with. the method i use is the dodgy method of fflush (stdin) and that is only because its quick and simple to use, and my compiler supports it - i don't ever have to write portable code and that is probably a limitation on my experience. the only instance in which i use said method is if i want to use a getchar after a scanf, for string input i always use fgets.

    i will however be wise in telling you to investigate flushing the input buffer for yourself and use a method which you are comfortable with and suits your own circumstances - what works for me may might be totally unsuitable in your field
    No No's:
    fflush (stdin); gets (); void main ();


    Goodies:
    Example of fgets (); The FAQ, C/C++ Reference


    My Gear:
    OS - Windows XP
    IDE - MS Visual C++ 2008 Express Edition


    ASCII stupid question, get a stupid ANSI

  6. #6
    Sr. Software Engineer filker0's Avatar
    Join Date
    Sep 2005
    Location
    West Virginia
    Posts
    235
    Specifically, the segmentation fault is because, when you search for the character ch (which is '\n', as pointed out in another post by Richie T) in the buffer a (which has no '\', ibid) using strchr(), it's not being found and strchr() returns NULL, which you are then passing to puts(). puts() tries to access the string pointed to by NULL and you get your segfault.
    Insert obnoxious but pithy remark here

  7. #7
    The Richness... Richie T's Avatar
    Join Date
    Jan 2006
    Location
    Ireland
    Posts
    469
    i didnt get a chance to reply sooner because i was disconnected while i was in the middle of typing a reply. needless to say it was big and i don't really feel like retyping it, so here's what i'll do:

    filker0 is bang on in what he said - the segmentation error is because of the character not being found. that is why in the link to the example of fgets uses this code:

    Code:
    if ((p = strchr(buf, '\n')) != NULL)
    *p = '\0';
    what happens with strchr is that it returns a pointer to the memory location in which the search item is found - if nothing is found it returns NULL. see that in the above snippet, the only time that an operation involving p is performed, it is in the case of the pointer NOT being equal to NULL -search found something!

    now i hope that we all have managed to shed some light on your problem, but i get the feeling that its possible that we havent. the code you supplied last still doesnt work, and suggesting further ways to proceed might be a little convoluted, so against my normal policy of trying to help someone realise how to solve the problem, i will instead post code of how i would go about my interpretation of what your goal is (i'm pretty sure that you want to search a string for a certain character). here it is:

    Code:
    #include<stdio.h>
    #include<string.h>
    
    int main()
    {
            char a[100];
    	char *p;
            int ch;
    
            printf("Enter a string: ");
    	fgets (a,100,stdin);		/*using fgets despite using scanf below,
    					the reason? i dont have to flush the input,
    					i do need to take care of the possibility
    					of a newline, as follows */
    
    	if ((p = strchr(a,'\n')) != NULL)	/*trust me when i say to always use an if statement when calling strchr*/
    		*p = '\0';			/*sets newline character (if found) to string terminator character*/
    
            printf("Now enter a single character which you want to search for: ");
            scanf ("%c", &ch); /*you could even use fgets here again, limited to one character*/
    
            if ((p = strchr(a,ch)) != NULL)		/*now searching for the character*/
    	        printf ("Character %c was found", *p);
    	else
    		printf ("Character was not found");
    
            return 0;
    }
    No No's:
    fflush (stdin); gets (); void main ();


    Goodies:
    Example of fgets (); The FAQ, C/C++ Reference


    My Gear:
    OS - Windows XP
    IDE - MS Visual C++ 2008 Express Edition


    ASCII stupid question, get a stupid ANSI

  8. #8
    The superhaterodyne twomers's Avatar
    Join Date
    Dec 2005
    Location
    Ireland
    Posts
    2,273
    also, I think you forgot your '&' when you were scanning:

    Code:
    scnaf("%c", &a);
    without the & it won't work

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. scanf() consideres useless
    By Snafuist in forum C Programming
    Replies: 15
    Last Post: 02-18-2009, 08:35 AM
  2. Help with a basic scanf procedure.
    By killpoppop in forum C Programming
    Replies: 9
    Last Post: 11-03-2008, 04:39 PM
  3. scanf issue
    By fkheng in forum C Programming
    Replies: 6
    Last Post: 06-20-2003, 07:28 AM
  4. Scanf and integer...
    By penny in forum C Programming
    Replies: 3
    Last Post: 04-24-2003, 06:36 AM
  5. scanf - data is "put back" - screws up next scanf
    By voltson in forum C Programming
    Replies: 10
    Last Post: 10-14-2002, 04:34 AM