NO

Author Topic: scanf, and gets problems  (Read 2232 times)

silvia

  • Guest
scanf, and gets problems
« on: December 31, 2011, 04:31:51 PM »
My program is:
/****************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void main()
{
char str[80];
FILE *fp;                                         

if((fp = fopen("Taxi Information.txt", "w"))==NULL)

printf("Cannot open file.\n");                                     exit(1);                                                    
}
do {                                                 
 printf("Enter a string (CR to quit):\n");               
scanf_s("%s", str);   // Type  slivia todorof                           
 gets(str);                                                       
strcat(str, "\n");                                                       
} while(*str!='\n');                                                      
}
/****************************************/
If I type:  silvia todorof   , I have two problems:
1st problem: After typing "silvia todorof", appears "Enter a string (CR to quit)", as required, but if I hit Enter it did not quit and stuck there; but it goes out if I write ^z  with two times Enter.
2nd problem: the text file is empty.

Thanks
Silvia


CommonTater

  • Guest
Re: scanf, and gets problems
« Reply #1 on: December 31, 2011, 05:40:55 PM »
Hi Silvia....

You should look up the scanf_s()  and gets() functions in the help file... this is easy just put your typing cursor on the coloured keyword and press F1 on your keyboard... this works for all coloured keywords, btw.

It appears to hang because you are actually calling two functions that need inputs. 
Your output file is empty because you never actually write anything to it.
It gets stuck in a loop because you are doing all this in a loop that isn't going to exit since str will never be a single \n when you are adding your own \n after the one you type.

Best bet... sit down with a pencil and paper and jot up a real quick step by step procedure describing what you want to do... the smaller the steps the better... Then you just translate your procedure to code.

Also note...
The minimum program skeleton in C99 is....
Code: [Select]
int main (void)
   {
       // your code goes here
       
       return 0;
   }
This is because the Operating System expects an integer errorlevel when main() ends.  This is both used internally by the operating system and made available to batch files and other functions.  Your code may work well enough with void main() but it will incorrectly interfaced with the operating system and in some cases may cause problems in batch files and parent programs.

Many older programming books use void main() which is not ok. 
Pay attention to your compiler's warnings and errors ....