problems with scanf() and gets()

Darwin Ling darwinl at alliance.uucp
Fri Jun 7 05:10:35 AEST 1991


In article <2759 at apss.apss.ab.ca> jhp at apss.ab.ca (Herbert Presley) writes:
>
>I am a new C programmer and I've been trying to get an answer through the net 
>for the following problem.  Unfortunately, my postings don't seem to be getting
>through for some reason.
>
>I kinda feel intimidated because, like most new programmers, I am probably
>asking a question that has a VERY simple response, and I can't help but feel
>that it's a problem that I am creating by my lack of knowledge.
>
>For your information, I run a Turbo C compiler on an XT (true) compatible.
>
>scanf() and gets() will not accept keyboard input in the same program if
>scanf() is used first.  I am using scanf() to accept an integer from the
>keyboard and gets() to accept a string.  Because scanf() aborts input at
>the first whitespace, you cannot enter a sentence string (or, is this something
>I am doing wrong because of my inexperience)?  So in instances where you are
>attempting to enter a formatted integer variable and a string in the same
>program, I find that using scanf() first makes gets() skip the wait for
>keyboard input.
>
>Unfortunately, I have no mentor in my world who knows very much about C.  I
>began with C through a couple of courses at our local Technical College and
>they don't seem to offer a great deal of ongoing support.
>___________________________________________________________________________
>
>    email : jhp at apss.ab.ca 
>     mail : c/o APSS, 10320 - 146 St., Edmonton, Alberta, Canada  T5N 3A2 
>    phone : (403) 451-7151


You can try the following :

   Use fgets to get whatever from the standard input....

   For string, if the last string character is a '\n' , ie a newline
   character, replace it with '\0'. You can find the last character's
   position by strlen (str) - 1 . 

   For integer , do the same thing to eliminate the '\n' , then 
   convert the integer string to integer using 

   sscanf (str, "%d", &integer_value)

   str is the string you get from fgets.. 
   sscanf works exactly the same as scanf except sscanf scans from a string,
   while scanf scans its input from the standard input...
   You can use the desired format for the integer

   Hope that helps


------------------------------------------------------------------
				Darwin Ling                       

				Alliance Technologies , Inc
				Advanced Development group
				uunet :     uunet!alliance!darwinl
------------------------------------------------------------------



More information about the Comp.lang.c mailing list