繁体   English   中英

请帮忙调试C程序

[英]Please help debug C program

编写一个提示用户输入的 C 程序

  • 学生卡
  • 姓名
  • 生日

运行程序并将输入的数据存储在一个以学号命名的doc文件中。
提示:使用结构。

问题:月、日、年的output后程序停止运行

#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;
}

我认为您的意思是该程序似乎在year值的输入(而不是输出)之后停止。

这是因为scanf调用中的尾随换行符:

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

这将导致scanf读取并忽略任何尾随空格。 但是要知道空格何时结束,必须有一些非空格输入,你不输入(我猜)。

解决方案很简单:切勿在scanf格式字符串中使用尾随空格字符(换行符是空格字符):

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

您必须使用 fprintf 将 output 打印到文件中。 删除最后一个 scanf 语句中的 \n 字符。 在 fopen 语句中删除文件夹名称。 output 文件将自动存储在您当前的代码目录中。

PFA 代码。

#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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM