Problem with loop

This is a discussion on Problem with loop within the C Programming forums, part of the General Programming Boards category; Hi! I make a input form with loop. The idea is, if the user has finished to fill the input ...

  1. #1
    Registered User
    Join Date
    Dec 2011
    Posts
    10

    Problem with loop

    Hi! I make a input form with loop. The idea is, if the user has finished to fill the input form, then the program will ask is the user will input again or not. If yes, then the input form will appear again, if not the program will close. But, I got an error (Processor fault) when I run my program. Can someone help me to fix my code?

    this is code that I've made:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <conio.h>
    
    typedef struct dokter{
        char sNip[10];
        char fName[15];
        char lName[15];
        char sAlmt[30];
        char sTgl[15];
        char sSex[3];
        char sSpec[30];
        int sav;
    } d;
    
    main()
    {
        d doct[50];
        int z;
        char cAgain = 'y';
    
        for (z = 0; cAgain = 'y' ; z++)
        {
            clrscr();
            gotoxy(20,5);printf("*******************************************");
            gotoxy(20,6);printf("+**=======>> Input data doctor <<=======**+");
            gotoxy(20,7);printf("||=======================================||");
            gotoxy(20,8);printf("                                           ");
            gotoxy(20,9);printf("1. Insert NIP                            ");
            scanf("%s", doct[z].sNip);
            gotoxy(20,10);printf("2. Insert First Name: ");
            scanf("%s", doct[z].fName);
            gotoxy(20,11);printf("3. Insert Last Name: ");
            scanf("%s", doct[z].lName);
            gotoxy(20,12);printf("4. Insert Address: ");
            scanf("%s", doct[z].sAlmt);
            gotoxy(20,13);printf("5. Insert Birth Date [dd/mm/yyyy]: ");
            scanf("%s", doct[z].sTgl);
            gotoxy(20,14);printf("6. Sex: ");
            scanf("%s", doct[z].sSex);
            gotoxy(20,15);printf("7. Specialist: ");
            scanf("%s", doct[z].sSpec);
            gotoxy(20,16);printf("\n Input Again [y/t]? ");
            scanf("%c", &cAgain);getch();
         
          }
          if(cAgain == 'n')
            exit(1);
    
    }

  2. #2
    language hopper dennis.cpp's Avatar
    Join Date
    Jan 2011
    Location
    Herborn, Hesse, Germany
    Posts
    197
    Take a close look at your scanf statements.
    Hardware: Intel® Core™ i7-3630QM CPU @ 2.40GHz × 8
    Operating system: Debian Testing/Jessie / Linux 3.16-2-amd64 / KDE SC 4.14.1
    Compiler: gcc 4.9.1-16 with KDevelop 4.7.0

  3. #3
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    You want ==, not =.

    Code:
       for (z = 0; cAgain = 'y' ; z++)
    That would not cause the fault tho. Does it happen right away, or at a specific point?

    I would put a hard limit on your string reads to match the size of the fields, eg:

    Code:
    typedef struct dokter{
        char sNip[10];
        char fName[15];
    
    [...]
    
            gotoxy(20,9);printf("1. Insert NIP                            ");
            scanf("%9s", doct[z].sNip);
            gotoxy(20,10);printf("2. Insert First Name: ");
            scanf("%14s", doct[z].fName);
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  4. #4
    Registered User
    Join Date
    Dec 2011
    Posts
    10
    Thanks for the reply...

    @ dennis.cpp can you tell me more specific about the scanf statements?

    I try to remove the scanf and the for loop, and I can run my program. But when I include the scanf, then I got a processor fault.
    Sorry for my bad english.

  5. #5
    Registered User
    Join Date
    Dec 2011
    Posts
    795
    I would do something about the size of your struct: one takes up 122 bytes, but having an array of fifty means that you're allocating 6100 bytes solely on the stack, something that's generally a terrible idea. There are many ways to get around this issue, dynamic allocation being the best (realloc if the user wants to enter more data).

    Also, what happens when someone decides to enter a name that's longer than fifteen characters? Scanf will not catch the error without crazy formatting like MK27 said (so use fgets), and you'll most likely crash or corrupt memory elsewhere.

    Finally, I'm not sure why you keep using gotoxy, as it's wasteful and definitely not portable. It's easier to format your printfs with '\n' characters.

  6. #6
    Registered User
    Join Date
    Dec 2011
    Posts
    10
    Thanks for your help, I will try it.

  7. #7
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,308
    I love how sSex is only long enough to hold a two-character string. I guess the only thing that fits is "m", "f", or "no".
    "yes", "male", or "female" certainly wont fit!

    Note that to prevent buffer overruns you should put numbers in your scanf strings like:
    Code:
    scanf("%9s", doct[z].sNip);
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  8. #8
    Registered User
    Join Date
    Dec 2011
    Posts
    10
    Thanks for your explanation @iMalc this is so helpful.

  9. #9
    Third Eye Babkockdood's Avatar
    Join Date
    Apr 2010
    Posts
    352
    Maybe this wouldn't work in this case, but I've always used fgets(str, sizeof(str), stdin) to get strings from stdin.

    And your main function should look like this:

    Code:
    int main(void) {
        // code...
        return 0;
    }
    Assuming your program returned successfully, of course. FAQ > main() / void main() / int main() / int main(void) / int main(int argc, char *argv[]) - Cprogramming.com
    Quote Originally Posted by The Jargon File
    Microsoft Windows - A thirty-two bit extension and graphical shell to a sixteen-bit patch to an eight-bit operating system originally coded for a four-bit microprocessor which was written by a two-bit company that can't stand one bit of competition.

  10. #10
    Registered User
    Join Date
    Dec 2011
    Posts
    10
    Thanks for the information Babkockdood.
    I was change my scanf to fgets, but I got some problem. when I run my program, the first input "insert NIP" was skipped/I can't input NIP. so, the input start from "First Name".

    this is my revised code:
    Code:
    gotoxy(20,5);printf("*******************************************");
            gotoxy(20,6);printf("+**=======>> Input data dokter <<=======**+");
            gotoxy(20,7);printf("||=======================================||");
            gotoxy(20,8);printf("                                           ");
            gotoxy(20,9);printf("1. Input NIP                            ");
            fgets(doct[z].sNip, 9, stdin);
            gotoxy(20,10);printf("2. Insert first name: ");
            fgets(doct[z].fName, 14, stdin);
            gotoxy(20,11);printf("3.Insert Last Name: ");
            fgets(doct[z].lName, 14, stdin);
            gotoxy(20,12);printf("4. Insert Address: ");
            fgets(doct[z].sAlmt, 29, stdin);
            gotoxy(20,13);printf("5. Insert Birth Date [dd/mm/yyyy]: ");
            fgets(doct[z].sTgl, 14, stdin);
            gotoxy(20,14);printf("6. Sex: ");
            fgets(doct[z].sSex,2, stdin);
            gotoxy(20,15);printf("7. Specialist: ");
            fgets(doct[z].sSpec, 29, stdin);
            //doct[z].sav = 0;
            gotoxy(20,16);printf("\n Input again [y/t]? ");
            scanf("%c", &cLagi);getch();
            readData(z);

  11. #11
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,762
    > scanf("%c", &cLagi);getch();
    If you're going to use fgets(), then you have to use if for everything.
    Adding random hackery to try and keep the input stream in sync will just make a mess of the code, and probably won't work in the long run.

    Also, mixing in conio functions like getch() isn't likely to help either. There's no reason to believe that conio and stdio are synchronised.
    Meaning that stdio could have buffered something that conio knows nothing about.

    > fgets(doct[z].sNip, 9, stdin);
    If you're going to use fgets(), then use a temporary buffer.
    If your user types in more than 7 characters (plus a newline, plus a \0 for free), then you're all out of sync again.
    Code:
    char buff[BUFSIZ];
    fgets( buff, sizeof buff, stdin );
    // remove \n, if that is important
    if ( strlen(buff) < 9 ) {
        strcpy( doct[z].sNip, buff );
    } else {
        // error message?
    }
    > when I run my program, the first input "insert NIP" was skipped/I can't input NIP. so, the input start from "First Name".
    That's because some prior scanf() left a \n on the input stream which you haven't accounted for.

    > gotoxy(20,5);
    Until your program is actually finished and WORKING, all this eye candy is a distraction (and a waste of effort). It clutters up the code, and you keep updating it as the rest of the program evolves.
    Nobody paints a house while it is still being built.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  12. #12
    Registered User
    Join Date
    Dec 2011
    Posts
    10
    So, I should use if on every input? sorry I never use fgets before.

  13. #13
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,762
    The key is consistency.
    A mix-and-match approach using scanf, getchar etc will just lead to problems in the long run.


    > So, I should use if on every input? sorry I never use fgets before.
    Create a small test program, and practice using fgets()
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Loop problem?
    By benrogers in forum C Programming
    Replies: 9
    Last Post: 02-08-2011, 12:26 AM
  2. while loop problem
    By xniinja in forum C Programming
    Replies: 2
    Last Post: 08-20-2010, 06:28 AM
  3. loop problem
    By eagle0eyes in forum C Programming
    Replies: 7
    Last Post: 05-29-2010, 03:14 PM
  4. Problem in the loop
    By PunchOut in forum C Programming
    Replies: 2
    Last Post: 11-30-2008, 03:17 PM
  5. Problem with WHILE loop.
    By kinghajj in forum C Programming
    Replies: 3
    Last Post: 11-20-2003, 06:07 PM

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