Thread: Need help, code stops

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Dec 2023
    Posts
    13

    why backspace in scanf function ?

    Hi need your help again ...

    Code:
    #include <stdio.h>
    #include <string.h>
     
    typedef struct
    {
        char phone[30];
        char name[30];
    }
    Phonebook;
    Phonebook people[2];
    
    int showfile(void);
    
    int main()
    {
    
        //open file & user input
        FILE *file = fopen("phonebook.txt", "w");
        
        for(int i = 0; i < 2; i++)
        {
            printf("Name [%d] ?: ", i+1);
            scanf(" %[^\n]", people[i].name);
            
            printf("Phone [%d] ?: ", i+1);
            scanf("%s", people[i].phone);
    
            fprintf(file, "Name: %s\t Phone: %s\n", people[i].name, people[i].phone);
        }
        fclose(file);
    
        //ask user to read file
        char decision;
        printf("\nShow File ? (y/n): ");
        scanf("%c", &decision);
    
        if(decision == 'y')
        showfile();
            else if(decision == 'n')
            printf("Quit\n");
    
    return 0;
    }
    
    //// FUNCTIONS ////
    ///////////////////
    
    int showfile(void)
    {
        FILE *fh_output = fopen("phonebook.txt", "r");
    
        if(fh_output != NULL)
        {
            char c;
            while((c = fgetc(fh_output)) != EOF)
            putchar(c);
        }
        fclose(fh_output);
        return 0;
    }
    The problem was that the code always stopped after
    //ask user to read file
    printf("\nShow File ? (y/n): ");
    scanf("%c", &decision);

    It didnt let me type in anything if I didnt have a backspace in front of "%c" in the scanf function but if I remove the code above I dont need a backspace, why is that the case ? Whats the deal with the backspace in front of it ? Someone explained it to me once but I still dont get it.

    Thanks in advance.
    Last edited by crusher152; 02-04-2024 at 05:47 AM. Reason: chanegd question

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. what is wrong with my code, my program stops
    By aqoonyahan in forum C Programming
    Replies: 2
    Last Post: 02-23-2016, 01:06 AM
  2. Replies: 8
    Last Post: 03-29-2010, 04:38 AM
  3. Client/server problem; server either stops receiving data or client stops sending
    By robot-ic in forum Networking/Device Communication
    Replies: 10
    Last Post: 02-16-2009, 11:45 AM
  4. Stops before the end of the code.
    By Elivmar in forum C++ Programming
    Replies: 14
    Last Post: 10-08-2005, 01:56 PM
  5. This never stops for some reason
    By Shadow12345 in forum C++ Programming
    Replies: 14
    Last Post: 09-02-2002, 10:41 AM

Tags for this Thread