我在while循环中遇到了如何获取字符串并且只显示名称major和GPA作为列表的问题。另外我需要fgets
函数的帮助,因为每一行每三行不同,所以如何在列表中显示它们。我将在while
循环中放入什么来使其工作?
#include <stdio.h>
int main(void)
{
FILE *cfPtr;
FILE *ofp;
char name[20];
char major[3];
double gpa;
ofp = fopen("outputFile.txt","w");
fprintf(ofp,"Name\tMajor\tGPA\n");
if((cfPtr = fopen("inputFile.txt","r")) == NULL)
{
printf("This file could not be opened\n");
}
else
{
while (!feof(cfPtr))
{
fgets(name, 20, cfPtr );
//How to read the string and only display
//the name major and gpa?
//fprintf(ofp,"%s\t%s\t%f\n", name, major, gpa);
}
}
fclose(cfPtr);
fclose(ofp);
}
输入文件是:
Name: John Milton
Major: EE
GPA: 3.98
Name: Karl Lewis
Major: CS
GPA: 3.6
Name: Homer Simpson
Major: CE
GPA: 4.0
我需要输出文件:
Name: Major: GPA:
John Milton EE 3.98
Karl Lewis CS 3.6
Homer Simpson CE 4.0
答案 0 :(得分:1)
嗨,你可以这样做。如果你必须使用fegts。
你应该声明这些char数组,
char name[20];//enough long
char major[10];//enough long
char gpa[10];//enough long
char name_tag[7];//According to the "Name: "
char major_tag[8];//According to the "Major: "
char gpa_tag[6];//According to the "GPA: "
和while循环,
while (1)
{
if(fgets(name_tag,7,cfPtr) == NULL)
break;
if (feof(cfPtr))
{
break;
}
if(fgets(name, 20, cfPtr ) == NULL)
break;
if (name[strlen(name) - 1] == '\n')
{
name[strlen(name) - 1] = '\0';//remove '\n'
}
if(fgets(major_tag,8,cfPtr) == NULL)
break;
if(fgets(major,10,cfPtr) == NULL)
break;
if (major[strlen(major) - 1] == '\n')
{
major[strlen(major) - 1] = '\0';
}
if(fgets(gpa_tag,6,cfPtr) == NULL)
break;
if(fgets(gpa,10,cfPtr) == NULL)
break;
if (gpa[strlen(gpa) - 1] == '\n')
{
gpa[strlen(gpa) - 1] = '\0';
}
fprintf(ofp,"%s\t%s\t%s\n", name, major, gpa);
}
答案 1 :(得分:0)
示例代码:
#include <stdio.h>
typedef struct data {
char name[20];
char major[3];
double gpa;
} Data;
Data *fgets_data(Data *aData, FILE *fp){
if( fscanf(fp, "Name: %19[^\n]%*c", aData->name)==1 &&
fscanf(fp, "Major: %2s%*c", aData->major)==1 &&
fscanf(fp, "GPA: %lf%*c", &(aData->gpa))==1 )
return aData;
return NULL;//fail
}
void fputs_data(Data *aData, FILE *fp){
if(aData == NULL) //print caption
fprintf(fp, "%-20s%-8s%s\n",
"Name:", "Major:", "GPA:");
else
fprintf(fp, "%-20s%-8s%g\n",
aData->name, aData->major, aData->gpa);
}
int main(void){
FILE *cfPtr;
Data aData;
if((cfPtr = fopen("inputFile.txt","r")) == NULL){
fprintf(stderr, "This file could not be opened\n");
} else {
FILE *ofp = fopen("outputFile.txt","w");
fputs_data(NULL, ofp);//print fileld name
while (fgets_data(&aData, cfPtr)!=NULL)
fputs_data(&aData, ofp);
fclose(ofp);
fclose(cfPtr);
}
return 0;
}
答案 2 :(得分:-1)
我不会为您编写代码,但我会帮您构建一些解决方案。
如果您查看输入文件和预期的输出格式,可能会这样:
open input and output files
while there are more lines in the input file
name = readline(); major = readline(); gpa = readline();
writeLine(name, major, gpa);
close files
现在,它只是一次确定每个步骤的代码。