嘿fellas在这里编写代码并且我有点失落。
int main()
{
FILE *fp;
struct info
{
char name[15];
char surename[15];
char gender[15];
char education[15];
} info;
char c;
int i, j, a;
struct info sem;
beginning:
scanf("%d", &a);
if(a==1)
{
fp = fopen("info.txt", "r");
for(i=0;!feof(fp);i++)
{ fscanf(fp, "%s %s %s %s",
sem.name,
sem.surname,
sem.gender,
sem.education,);
printf("%s, %s, %s, %s\n",
sem.name,
sem.surname,
sem.gender,
sem.education,);
}
fclose(fp);
goto beginning;
}
if (a == 2)
{
FILE *fp = fopen("info.txt", "r");
char tmp[256] = { 0x0 };
while (fp != NULL && fgets(tmp, sizeof(tmp), fp) != NULL)
{
if (strstr(tmp, "bachelors"))
/* Code works fine until this part */
fprintf(fp, "\n%s %s %s %s %s %s",
sem.name, sem.surname, sem.gender, sem.education,);
}
if (fp != NULL)
fclose(fp);
goto beginning;
}
在找到字符串“bachelor”之后,它应该打印出它找到它的行的其余部分,在这种情况下,用户身份的姓名,姓氏等等,但它没有,如果有人能指出我的错误,id非常好!
答案 0 :(得分:0)
执行以下操作:
1.修改结构
2.在代码中删除GOTO
(这是一个糟糕的编程标准)
3.正确的代码缩进
浏览下面的代码
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
struct info
{
char name[15];
char surname[15];
char gender[15];
char education[15];
} sem;
FILE *fp=NULL;
int i, a;
char tmp[256] = {0x0};
while(1)
{
printf("Enter the value\n");
scanf("%d", &a);
if((fp = fopen("info.txt", "r")) != NULL)
{
switch(a) // assuming your code is just an snippet and actual code has more than 2 conditions
{ // use if-else if just 2 condition checks
case 0:
exit(0); // quit the program
case 1:
for(i=0;!feof(fp);i++)
{
fscanf(fp, "%s %s %s %s", sem.name, sem.surname, sem.gender, sem.education);
printf("%s, %s, %s, %s\n",sem.name,sem.surname,sem.gender,sem.education);
}
break;
case 2:
while (fgets(tmp, sizeof(tmp), fp) != NULL)
{
if (strstr(tmp, "bachelors"))
{
/* Code works fine until this part */
fprintf(fp, "\n%s %s %s %s", sem.name, sem.surname, sem.gender, sem.education);
}
}
break;
default: printf("Default statement");
}
fclose(fp);
}
}
}