c语言 怎么将输入的数字限制在六位啊
答案:2 悬赏:0 手机版
解决时间 2021-04-18 21:17
- 提问者网友:黑米和小志
- 2021-04-18 07:14
c语言 怎么将输入的数字限制在六位啊
最佳答案
- 五星知识达人网友:山河有幸埋战骨
- 2021-04-18 08:43
按照你的要求,修改了一下:
#include
#include
#include
struct customer
{
char name[50];
char address[100];
char phone[20];
char PIN[10];
};
void new_customer()
{
struct customer a;
struct customer *p = &a;
FILE *fp1;
char filename[20] = {0};
int i;
memset(&a, 0, sizeof(struct customer));
printf("please enter file name
");
gets(filename);
if((fp1=fopen(filename,"w"))==NULL)
{
printf("cannot open file
");
exit(0);
}
printf("please input your name:
");
gets(p->address);
printf("please input your address:
");
gets(p->address);
printf("please input your telephone number:
");
gets(p->phone);
printf("please input your PIN:
");
scanf("%6s", p->PIN);
for (i = 0; i < 6; i++)
{
if (p->PIN[i] < '0' || p->PIN[i] > 9)
{
printf("Your PIN is incorrect.
");
fclose(fp1);
return ;
}
}
fwrite(p->address, 1, strlen(p->address), fp1);
fwrite(" ", 1, 1, fp1);
fwrite(p->phone, 1, strlen(p->phone), fp1);
fwrite(" ", 1, 1, fp1);
fwrite(p->PIN, 1, strlen(p->PIN), fp1);
fclose(fp1);
}
int main(void)
{
new_customer();
return 0;
}测试截图:
提示字符太多,就不写注释了。
#include
#include
#include
struct customer
{
char name[50];
char address[100];
char phone[20];
char PIN[10];
};
void new_customer()
{
struct customer a;
struct customer *p = &a;
FILE *fp1;
char filename[20] = {0};
int i;
memset(&a, 0, sizeof(struct customer));
printf("please enter file name
");
gets(filename);
if((fp1=fopen(filename,"w"))==NULL)
{
printf("cannot open file
");
exit(0);
}
printf("please input your name:
");
gets(p->address);
printf("please input your address:
");
gets(p->address);
printf("please input your telephone number:
");
gets(p->phone);
printf("please input your PIN:
");
scanf("%6s", p->PIN);
for (i = 0; i < 6; i++)
{
if (p->PIN[i] < '0' || p->PIN[i] > 9)
{
printf("Your PIN is incorrect.
");
fclose(fp1);
return ;
}
}
fwrite(p->address, 1, strlen(p->address), fp1);
fwrite(" ", 1, 1, fp1);
fwrite(p->phone, 1, strlen(p->phone), fp1);
fwrite(" ", 1, 1, fp1);
fwrite(p->PIN, 1, strlen(p->PIN), fp1);
fclose(fp1);
}
int main(void)
{
new_customer();
return 0;
}测试截图:
提示字符太多,就不写注释了。
全部回答
- 1楼网友:白昼之月
- 2021-04-18 10:22
你的struct *p未分配内存 这样写运行会出错 你可以malloc一下 结束前free掉
可以把结构里的int改成char,不然pin[20]可以存20个32位2进制数、、、、、、、、、
然后gets(p-〉pin),把上面的scanf后面的for循环str改成p->pin替换上去就可以了
至于写 fwrite((void*)p,sizeof(struct customer),1,fp)即可
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯