User Input to File

This is a discussion on User Input to File within the C Programming forums, part of the General Programming Boards category; I'm creating a program that should create a structure of a list of people entered by the user; the only ...

  1. #1
    Registered User
    Join Date
    Mar 2013
    Posts
    11

    Post User Input to File

    I'm creating a program that should create a structure of a list of people entered by the user; the only problem I'm having is with the %c. When I have it, the loop only occurs once; if I put a %s, the loop occurs up to 25 times, but it doesn't write to the text file. Here is the code:
    Code:
                                                                     #include<stdio.h>
    #include<stdlib.h>
    #include<string.h>
    
    struct person{
        char name[20];
        int age;
        struct person *next_ptr;
        } PERSON;
    
    int main (void){
    
    
    struct person PERSON;
    
    FILE *fp;
    char ans, ch;
    int ppl=0;
    
    fp=fopen("person_struct", "w");
    
    if(fp != NULL){
    
    while(ppl<25){
    
    
    printf("Would you like to add a person to the list? [y/n]  ");
    scanf("%c", &ans);
    
    if(ans == 'y') {
        printf("\nEnter a name:\n");
        scanf("%s", PERSON.name);
        fprintf(fp, "%s",PERSON.name);  
        printf("\nEnter age:\n"); 
        scanf("%i", &PERSON.age);
        fprintf(fp, "  %i\n", PERSON.age);
    } 
    else {
      ppl=25;       
    }
    
    ppl++;
    }
    fclose(fp);
    }   
    printf("\n\n\n");
    system("pause");
    return 0;
    }

  2. #2
    Registered User
    Join Date
    May 2012
    Posts
    1,066
    Code:
    scanf("%c", &ans);
    FAQ > How do I avoid a "dangling" newline when reading single character user input? - Cprogramming.com

    TL;DR
    You need a space before %c:
    Code:
    scanf(" %c", &ans);
    Bye, Andreas

  3. #3
    Registered User
    Join Date
    Mar 2013
    Posts
    11
    Wow, it's always the simplest things that get me. Thank you for helping me out.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. User input file
    By hotshotennis in forum C Programming
    Replies: 10
    Last Post: 10-09-2012, 01:00 AM
  2. Replies: 2
    Last Post: 03-05-2012, 09:35 AM
  3. User-specified input file issue.
    By ajrey92 in forum C Programming
    Replies: 5
    Last Post: 01-10-2011, 04:16 PM
  4. Replies: 3
    Last Post: 08-28-2010, 10:21 PM
  5. User input into a text file
    By Starr in forum C++ Programming
    Replies: 8
    Last Post: 01-10-2006, 07:52 PM

Tags for this Thread


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