gpt4 book ai didi

c - 带有整数和字符的字符串 - C

转载 作者:太空宇宙 更新时间:2023-11-04 04:59:12 25 4
gpt4 key购买 nike

#include <stdio.h>
#include<stdlib.h>

int main()
{
char first[10], last[10], id[10];
int stdnum;
FILE *fptr;
fptr = fopen("C:\\c\\program.txt","w");

if(fptr == NULL)
{
printf("Error!");
exit(1);
}

else
{

//first name
printf("Enter name: ");
scanf("%s", first);
fprintf(fptr,"%s ",first);


//last name
printf("Enter last name: ");
scanf("%s ", last);
fprintf(fptr,"%s", last);


//id
printf("Enter id: ");
scanf("%s %d", id, &stdnum);


fprintf(fptr,"%s\n", id);
fprintf(fptr,"%d\n", stdnum);

fclose(fptr);

return 0;
}
}

我正在编写一个程序,要求用户输入姓名、姓氏和学号。学号格式为小写字母后跟 8 位数字。当我运行这段代码时,我可以输入名字和姓氏。在我输入姓氏并在 cygwin 中按回车键后,控制台会给我一个空白行,我必须至少在其中键入一个字符或数字,以显示“输入学生 ID”。

Enter name: bob
Enter last name: jones




1
Enter id: a00998877

然后文件输出是这样的:

“鲍勃·琼斯11”

我希望输出是这样的:

“鲍勃·琼斯 a00998877”

我做错了什么?

最佳答案

为什么要在这一行扫描两个输入:

scanf("%s %d", id, &stdnum);

id 是一个 char 数组,可以保存字母数字输入。您可以删除 stdnum 的使用。

scanf("%s", id);

我有一个 example-with-stdin-stdout

关于c - 带有整数和字符的字符串 - C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42182355/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com