Reputation: 13930
I'm currently taking a course on "structured programming methods". The course is not language based, but we generally use either C or C++. Sometimes I'm required to write in one of these languages, sometimes I have to initially write in C and covert the code to C++, and sometimes I am allowed to write in what I prefer. Quite possibly odd, I prefer to utilize C's (f/p)rintf. So, here's my issue:
This is my header file for the 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;
Here's the "main".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;
}
I have tried a ton of combinations suggested by other questions/answers, but none seem to be dealing with a cross-language situation.
I'm basically looking for a solution that permits me to continue to use fprintf while leaving the bulk of the code C++.
I'm not looking for someone to code the solution for me, rather to explain what the issues are with this and how to logically go about circumventing them.
Also, typedef is a requirement. Thanks-
Upvotes: 3
Views: 5383
Reputation: 39208
std::string
has a c_str() const
method that you can use to "prep" a std::string
for formatting with %s
:
fprintf(fp, "%s", e->fullname.c_str());
When a printf-style function sees %s
in the format string, it is looking for a NUL-terminated C string (type: const char *
). The std::string::c_str() const
method returns just that for the std::string
object.
Upvotes: 3