撰寫一個提示用戶輸入的 C 程式
- 月
- 日
- 年
- 學生卡
- 名稱
- 生日
運行程式并將輸入的資料存盤在一個以學號命名的doc檔案中。
提示:使用結構。
問題:輸出月、日、年后程式停止運行
#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;
}
uj5u.com熱心網友回復:
您必須使用 fprintf 將輸出列印到檔案中。洗掉最后一個 scanf 陳述句中的 \n 字符。在 fopen 陳述句中洗掉檔案夾名稱。自動輸出檔案將存盤在您當前的代碼目錄中。
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;
}
uj5u.com熱心網友回復:
我認為您的意思是程式似乎在值的輸入(而不是輸出)之后停止year。
這是因為scanf呼叫中的尾隨換行符:
scanf("%d\n",&year);
這將導致scanf讀取并忽略任何尾隨空格。但是要知道空格何時結束,必須有一些非空格輸入,你不輸入(我猜)。
解決方案很簡單:永遠不要在scanf格式字串中使用尾隨空格字符(換行符是空格字符):
scanf("%d", &year); // Note lack of newline at the end of the string
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/407955.html
標籤:
上一篇:使用條件匹配來自不同表的2列
下一篇:回傳缺少對應型別的0個值
