Home > other >  Please help debug C program
Please help debug C program

Time:01-11

Write a C program that prompts a user to input

  • month
  • day
  • year
  • student ID
  • name
  • birthday

Run the program and store the data entered in a doc file which named by student number.
Tip: use structure.

Problem: The program stops running after the output of month, date and year

#include <stdio.h>
#include<string.h>
struct StudentData {
    char name[50];
    int id;
    int birth;
    char location[20];
}student;

int main() {
FILE * fPtr;
  fPtr = fopen("data/file1.txt", "w");

    int month, day, year;
    strcpy(student.name,"Diana");
    strcpy(student.location,"Ukraine");
    student.id=1820212026;
    student.birth=27052001;
    printf("Enter the № of month:\n");
    scanf("%d",&month);
    printf("Enter the day: ");
    scanf("%d",&day);
    printf("Enter the year: ");
    scanf("%d\n",&year);
    
    printf("The current date is: year-%d, month-%d, day-%d\n",year, month,day);
    printf("Student`s name is %s\n",student.name);
    printf("Student`s ID is %d\n",student.id);
    printf("Student`s birthday:%d\n",student.birth);
    printf("Student`s location is %s\n",student.location);
   

    return 0;
}

CodePudding user response:

You have to print output to a file using fprintf. Remove the \n character in last scanf statement. In fopen statement remove the folder name. Automatically output file will get stored in your current code directory.

PFA code.

#include <stdio.h>
#include<string.h>
struct StudentData {
    char name[50];
    int id;
    int birth;
    char location[20];
}student;

int main() {
FILE * fptr;
  fptr = fopen("file1.txt", "w");

    int month, day, year;
    strcpy(student.name,"Diana");
    strcpy(student.location,"Ukraine");
    student.id=1820212026;
    student.birth=27052001;
    printf("Enter the № of month:\n");
    scanf("%d",&month);
    printf("Enter the day: ");
    scanf("%d",&day);
    printf("Enter the year: ");
    scanf("%d",&year);

    fprintf(fptr,"The current date is: year-%d, month-%d, day-%d\n",year, month,day);
    fprintf(fptr,"Student`s name is %s\n",student.name);
    fprintf(fptr,"Student`s ID is %d\n",student.id);
    fprintf(fptr,"Student`s birthday:%d\n",student.birth);
    fprintf(fptr,"Student`s location is %s\n",student.location);

    fclose(fptr);

    return 0;
}

CodePudding user response:

I think you mean that the program seems to stop after the input (not output) of the year value.

This is because of the trailing newline in the scanf call:

scanf("%d\n",&year);

This will cause scanf to read and ignore any trailing space. But to know when the spaces ends, there must be some non-space input, which you do not input (I guess).

The solution is simple: Never use trailing space characters (and newline is a space character) in a scanf format string:

scanf("%d", &year);  // Note lack of newline at the end of the string
  •  Tags:  
  • Related