Writing void into a file with c++ - c++

i have the following code
void print(int & a, double & b, string & c)
{
cout << setprecision(2) << fixed;
const double GPA = a/b;
if(c == "Y")
{
cout << "\n\nTotal number of credit hours: " << a << endl;
}
else
{
cout << "\n*** Grades are being held for not paying the tuition. ***"
}
}
How can I write the cout in print(int, double, string) into a text file without tampering with print(int, double, string);? I tried something like this
ofstream file;
file.open("file.txt");
file << print(a,b,c);
file.close();
cout << "file created" << endl;
but this doesn't compile. Why not, and how do I fix it?

The way you've written it, your print() function is not capable of outputting to any given stream. This is because it hard-codes the stream that it writes to as cout.
If you want it to be able to write to any given stream, you have to parameterize the stream as another function parameter. For (1) convenience and (2) compatibility with existing code that assumes print() only takes three arguments and writes to cout, you can make the new parameter optional by defaulting it to cout:
void print(int& a, double& b, string& c, ofstream& os=cout) {
os << setprecision(2) << fixed;
const double GPA = a/b;
if (c == "Y") {
os << "\n\nTotal number of credit hours: " << a << endl;
} else {
os << "\n*** Grades are being held for not paying the tuition. ***";
}
}
Then you can call it as follows:
print(a,b,c,file);
The reason why your code doesn't compile is that you cannot pass void as a function argument or operator operand. When a function is declared as returning void, that means it does not return anything at all. There is no data returned by print() to stream to the ofstream. The streaming takes place inside the function, so it is only there that you can select the stream to which the output will be written.

bgoldst's answer solves the problem as asked, but I recommend a completely different solution. Stick your data in a class that has operator<< overloaded.
struct class_results {
int credits;
double GP_total;
bool tuition_paid;
};
std::ostream& operator<<(std::ostream& out, const class_results& c) {
if (c.tuition_paid) {
const double GPA = c.credits/c.GP_total;
out << "Total number of credit hours: ";
out << setprecision(2) << fixed << c.credits<< '\n';
} else
out << "\n*** Grades are being held for not paying the tuition. ***"
return out;
}
Then usage is slightly more normal:
class_results results = {num_credits,GPTottal,tuition};
ofstream file;
file.open("file.txt");
file << results;
file.close();
cout << "file created" << endl;

How can I write the cout in print(int, double, string) into a text file without tampering with print(int, double, string);?
You can't.
The function print is broken and you can't do what you want without fixing it.

Related

Passing reference of ostream as an function argument

I'm trying to create a function that will take ostream object as an argument, and then print to it. I plan to pass some of my fstream (files), and cout.
This is my code:
void printTask(int op1, int op2, int len, char operation, std::ostream& os = std::cout)
{
os << endl << " " << setw(len) << op1 << endl;
os << operation << " " << setw(len) << op2 << endl;
os << "-------------" << endl;
os << " ";
for(int i = 0; i < len; i++)
{
os << "?";
}
os << endl;
}
From main(), it goes like this...
ofstream output("output.txt", ios::out);
cout << addition(xyz, output) << endl;
and that function looks like this:
int addition(int xyz, ofstream file)
{
int op1 = ...;
int op2 = ...;
char choice = ...;
printTask(op1, op2, xyz, choice, file);
printTask(op1, op2, xyz, choice, cout); //this cout is not necessary, default parameter
}
I get an error about std::ios::base being private, but I did pass my ostream object by reference so it doesn't try to use copy constructor.
Any ideas?
EDIT: Wanted to update this with an answer. Prototype for addition was wrong, ofstream should be passed by reference, instead of copying it.
This works:
int addition(int xyz, ofstream& file) {...}
Big thanks to #Jarod42

Value-Returning Function Debug Error - C++

I am in a beginner C++ course. Here are the instructions for my assignment:
Write a program that calls a value-returning function that prompts the user to enter the weight of a person in pounds and then calls another value returning function to calculate the equivalent weight in kilograms. Output both the weights rounded to two decimal places. (Note that 1 kilogram = 2.2 pounds.) Format your output with two decimal places.
I thought everything was perfect. However, I am a getting a debug error, which is Runtime Check Error #3 - T. Please review my code and tell me what is wrong here. Remember, I am a beginner. Thank you.
#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>
using namespace std;
string get_date();
void student_heading();
float get_user_input(float);
float convert_weight(float);
int main()
{
cout << fixed << showpoint << setprecision(2);
string mydate;
float weight_lbs;
float weight_kgs;
mydate = get_date();
student_heading();
weight_lbs = get_user_input();
weight_kgs = convert_weight(weight_lbs);
return 0;
}
string get_date()
{
string mydate;
cout << "Enter today's date:";
getline(cin, mydate);
return mydate;
}
void student_heading()
{
cout << "*******************" << endl;
cout << "Student" << endl;
cout << "ID Number" << endl;
cout << "SYCS-135" << endl;
cout << "Assignment 6" << endl;
cout << "October 6, 2015" << endl;
cout << "******************" << endl;
}
float get_user_input(float lb_weight)
{
cout << "Please provide us with your weight, in pounds:";
cin >> lb_weight;
return lb_weight;
}
float convert_weight(float kg_weight)
{
float lb_weight;
kg_weight = lb_weight / 2.2;
return kg_weight;
}
Your error is that you are calling weight_lbs = get_user_input();
You cant call get_user_input with no argument because you do not have any function like that.
Your code has several issues.
Your function prototypes are not correct. The parameter in the braces have to contain the variable name as well as data type. So only function(int) is not enaugh, it should be function(int MyVariable). So the error was caused by calling function, which didn't exist, because your function prototype was not correct (expected a parameter).
Your get_user_input() function has a parameter which is not needed. The whole function should look like this:
float get_user_input()
{
cout << "Please provide us with your weight, in pounds:";
float lb_weight;
cin >> lb_weight;
return lb_weight;
}
Function for mass conversion can look like this:
float convert_weight(float lb_weight)
{
return lb_weight / 2.2;
}
Your main function then should look like this:
int main()
{
cout << fixed << showpoint << setprecision(2);
string mydate;
float weight_lbs;
float weight_kgs;
mydate = get_date();
cout << mydate << endl;
student_heading();
weight_lbs = get_user_input();
weight_kgs = convert_weight(weight_lbs);
cout << weight_kgs << "Kg";
getchar();
getchar();
return 0;
}
Don't forget to change the function prototypes to:
float get_user_input();
float convert_weight(float lb_weight);

C++ help setting up pointers in classes

I'm currently having some problems with my class and the member functions, particularly with taking the users input from the setter functions and then displaying that info from the print info function. I have a separate functions that allow the user to enter information about the character and then a getter function to then use in printing out the info that the user entered. When I first ran it I had an error about needing to use a pointer to a member function and I added the &Character::GetCharacterName and the others in my print info function. Now when I run the program through my main function (I didn't include it because it simply calls all the functions) my program will run but all the values are set at 1 no matter what the user entered. I know it has something to do with pointers so any help with correctly setting this up so that it returns the values that the user entered would be appreciated. Thanks
Character.h file
class Character
{
public:
Character();
void SetCharacterName();
void SetCharacterType();
void SetCharacterLevel();
string GetCharacterName();
string GetCharacterType();
double GetCharacterLevel();
void PrintInfo();
private:
string CharacterName;
string CharacterType;
double CharacterLevel;
};
Character.cpp file
Character::Character()
{
CharacterLevel = 1.0;
}
void Character::SetCharacterName()
{
cout << "\nWhat is the character's name? ";
cin >> CharacterName;
}
void Character::SetCharacterType()
{
cout << "\nWhat is the character's type? ";
cin >> CharacterType;
}
void Character::SetCharacterLevel()
{
cout << "\nWhat is the character's level? ";
cin >> CharacterLevel;
}
string Character::GetCharacterName()
{
return CharacterName;
}
string Character::GetCharacterType()
{
return CharacterType;
}
double Character::GetCharacterLevel()
{
return CharacterLevel;
}
void Character::PrintInfo()
{
system("pause");
system("cls");
cout << "\nCharacter name is " << &Character::GetCharacterName << ".\n";
cout << "\nCharacter type is " << &Character::GetCharacterType << ".\n";
cout << "\nCharacter level is " << &Character::GetCharacterLevel << ".\n";
}
Use (), to do a method call in PrintInfo:
cout << "\nCharacter name is " << GetCharacterName() << ".\n";
etc.
I sugest :
this->GetCharacterName();
In the print method.

Writing information in a structure to a file

Alright so i have these two structures, Im sending them down to a function to be saved to a txt file.
struct Cost
{
double hours;
double cost;
double costFood;
double costSupplies;
};
struct Creatures
{
char name[50];
char description[200];
double length;
double height;
char location[100];
bool dangerous;
Cost management;
};
This is the part of the function im confused on, i don't know how to take each line of this structure and write it to the file. Can someone explain to me how to do this?
file.open(fileName, ios::out);
if (!file)
{
cout << fileName << " could not be opened." << endl << endl;
}
else
{
fileName << c.name
<< c.description
<< c.lenght
<< c.height
<< c.location
<< c.dangerious
<< c.management.hours
<< c.management.cost
<< c.management.costFood
<< c.management.costSupplies;
file.close();
cout << "Your creatures where successfully save to the " << fileName << " file." << endl << endl
<< "GOODBYE!" << endl << endl;
}
}
If you want a solution like what you wrote in your question all you need to do is put and end line after each attribute you write out.
fileName << c.name << std::endl
<< c.description << std::endl
...
As long as the information you were trying to output is all that is going in the file this should work.
Then you can read them back in in the order you wrote them. Just be careful when reading back in strings which might have spaces in them.
You need to write the overloaded operator << for your defined classes Cost and Creatures.
class Cost {
public:
friend std::ostream& operator<< (std::ostream& o, const Cost& c);
// ...
private:
// data member of Cost class
};
std::ostream& operator<< (std::ostream& o, const Cost& c)
{
return o << c.hours<<"\t"<<c.cost<<"\t"<<c.costFood<<"\t"<<c.costSupplies<<std""endl;
}
Now you can use it as follows:
Cost c;
std::cout<<c<<"\n";
For detailed information about this concept, you can refer the ISOCPP FAQ link on this
http://isocpp.org/wiki/faq/input-output#output-operator

function does not take 1 arguments error

I've tried many times to fix this error but I'm not sure what to do. For both the addBooks and displayBooks functions I am getting a "function does not take 1 arguments" error, though the vector should just be one argument.
struct bookStruct
{
char title[40];
char author[40];
int pages;
int year;
};
enum menu { display=1, add, end} ;
void displayOptions();
void displayBooks();
void addBooks();
int main(){
vector<bookStruct> book(1);
string option = "display";
displayOptions();
cin >> option;
//std::strcpy(book[0].title, "a");
//std::strcpy(book[0].author, "a");
//book[0].pages = 0;
//book[0].year = 0;
while (option != "end"){
addBooks(book);
displayBooks(book);
}
return 0;
}
void displayOptions(){
cout << "1. Display list of books" << endl;
cout << "2. Add books" << endl;
cout << "3. Exit" << endl;
}
void displayBooks(vector<bookStruct> book){
for (int n = 0; n<book.size(); n++){
cout << book[n].title << " ; " << book[n].author << " ; "
<< book[n].pages << " ; " << book[n].year <<endl;
}
cout << endl;
}
void addBooks(vector<bookStruct> book){
int n = book.size()+1;
book.resize(book.size()+1);
cout << "Enter the book title: " << endl;
cin >> book[n].title;
cout << "Enter the author name: " << endl;
cin >> book[n].author;
cout << "Enter the number of pages: " << endl;
cin >> book[n].pages;
cout << "Enter the publication year: " << endl;
cin >> book[n].year;
}
Both addBooks and displayBooks take no arguments:
void displayBooks();
void addBooks();
yet you are calling them with arguments:
addBooks(book);
displayBooks(book);
The compiler is telling you this in its own words.
It looks like you need
void displayBooks(vector<bookStruct> book);
void addBooks(vector<bookStruct> book);
although it is more likely that you don't need to copy the vectors into the functions:
void displayBooks(const vector<bookStruct>& book);
void addBooks(const vector<bookStruct>& book);
Note you have definitions of one-parameter functions after main(). The main() function only considers the declarations that come before it.
void displayBooks();
void addBooks();
take no parameter, however you passed book into them, the compile cannot find both functions. therefore, error.
void displayBooks();
should be
void displayBooks(vector<bookStruct> book);
but as a better approach you can use:
void displayBooks(const vector<bookStruct> &book);
So that book vector is not copied while being passed into the method DisplayBooks
Your function is declared as
void addBooks();
but you are calling it with
addBooks(book);
Compiler obviously thinks it strange that you have no argument in the declaration, and then try to call it with an argument.
It is hard for me to advice exactly what you should do, since it's not clear from the code you have posted what the "right" thing is.