我是C语言新手。你能帮我一下吗?有一个结构名字,姓氏,性别,年龄。必须通过键盘输入条目。我需要将此信息保存在一个文件中,然后在屏幕上显示带有gender == Male的所有条目,并将它们保存在一个单独的文件中。谢谢你!
有一个从文件中读取结构的代码,但是我不明白如何检查性别==男性。
#include "stdafx.h"
#include <cstdio>
int _tmain(int argc, _TCHAR* argv[])
{
FILE *file;
struct Person {
char name[20];
char gender[20];
unsigned age;
};
struct Person SinglePerson[10];
char i=0;
file = fopen("e:\Test.txt", "r");
while (fscanf (file, "%s%s%u", SinglePerson[i].name, &(SinglePerson[i].gender), &(SinglePerson[i].age)) != EOF) {
printf("%s %s %un", SinglePerson[i].name, SinglePerson[i].gender, SinglePerson[i].age);
i++;
}
file = fopen("e:\fprintf.txt", "w");
while (scanf ("%s%s%u", SinglePerson[i].name, &(SinglePerson[i].gender), &(SinglePerson[i].age)) != EOF) {
fprintf(file, "%s %s %un", SinglePerson[i].name, SinglePerson[i].gender, SinglePerson[i].age);
i++;
}
fread;
return 0;
}
成功了!我做到了))
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define M 2 // M plus 1 is equals to number of structres
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
FILE *file;
struct Person {
char name[20];
char gender[20];
unsigned age;
};
struct Person SinglePerson[1];
char i=0;
char counter = 0;
void InputFromKeyboard () {
file = fopen("Input.txt", "w");
while(scanf("%s%s%u", SinglePerson[i].name, SinglePerson[i].gender, &(SinglePerson[i].age)) == 3 && i <= M) {
fprintf(file, "%s %s %un", SinglePerson[i].name, SinglePerson[i].gender, SinglePerson[i].age);
counter++;
i++;
if (i == M+1) {
break;
}
}
fclose(file);
};
void OutputToFile () {
file = fopen("Output.txt", "w");
for (i = 0; i < counter; i++) {
if (strcmp(SinglePerson[i].gender, "Male") == 0) {
fprintf(file, "%s %s %un", SinglePerson[i].name, SinglePerson[i].gender, SinglePerson[i].age);
}
}
fclose(file);
}
void OutputToScreen () {
file = fopen("Output.txt", "r");
for (i = 0; i < counter; i++) {
if (strcmp(SinglePerson[i].gender, "Male") == 0) {
printf("%s %s %un", SinglePerson[i].name, SinglePerson[i].gender, SinglePerson[i].age);
}
}
fclose(file);
}
int main(int argc, char *argv[]) {
InputFromKeyboard();
OutputToFile();
OutputToScreen();
return 0;
}