我目前正在參加「結構化編程方法」課程。該課程不是基於語言的,但我們通常使用C或C++。有時我需要使用其中一種語言編寫代碼,有時候我必須先用C編寫代碼並將代碼轉換爲C++,有時候我可以按照自己的喜好編寫代碼。很可能奇怪,我更喜歡使用C(f/p)rintf。所以,這裏是我的問題:如何使用fprintf打印頭文件中定義的結構成員值?
這是struct
我的頭文件:
#include <string>
using namespace std;
typedef string FNAME;
typedef string LNAME;
typedef string FULLNAME;
typedef struct EmpRecord
{
FNAME firstname;
LNAME lastname;
FULLNAME fullname;
float hours, rate, deferred, gross, netpay,
fedtax, statetax, ssitax;
} EmpRecord;
這裏的「主」的.cpp:
#define STRADD ", "
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include "Struct.h"
#include "Rates.h"
#include "calcTaxesPlus.cpp"
using namespace std;
/*......*/
void printEmpData(FILE *fp, struct EmpRecord *, float reghrs, float othrs);//3.8
/*......*/
int main()
{
float totRegHrs, totOtHrs, totRates, totGross, totDeferd,
totFed, totState, totSSI, totNet;
float reghrs, othrs;
float avgRate, avgRegHrs, avgGross, avgFed, avgSSI, avgNet,
avgOtHrs, avgState, avgDeferd;
int numEmp;
EmpRecord emp;
EmpRecord *Eptr;
Eptr = &emp;
FILE * fp;
fp = fopen("3AReport.txt", "w");
if (fopen == NULL)
{
printf("Couldn't open output file...!");
fflush(stdin);
getchar();
exit(-1000);
}
/*....*/
printEmpData(fp, Eptr, reghrs, othrs);//3.8
return 0;
}
/*....*/
void printEmpData(FILE *fp, struct EmpRecord *e, float reghrs, float othrs)
{
fprintf(fp, "\n%-17.16s %5.2f %5.2f %7.2f %6.2f %6.2f %7.2f", e->fullname, e->rate, reghrs, e->gross, e->fedtax, e->ssitax, e->netpay);
fprintf(fp, "\n %5.2f %6.2f %6.2f \n", othrs, e->statetax, e->deferred);
return;
}
我試圖通過提出一噸的組合其他問題/答案,但似乎沒有處理跨語言的情況。
我基本上尋找一種解決方案,允許我繼續使用fprintf,同時留下大量的代碼C++。
我並不是在尋找某人爲我編寫解決方案,而是爲了解釋這些問題以及如何從邏輯上繞過它們。
此外,typedef是一項要求。 Thanks-
不要'fflush(stdin)',這是未定義的行爲。 – ouah 2012-07-15 10:50:33