I think this is a pretty simple question, but I didn't find the answer.
I wish to write the result of a function to a file.
The file is open, and I'm able to write a simple string to it, but not the result of the function.
What I am missing?
#include <iostream>
#include <fstream>
using namespace std;
void addingtext(){
for (int i = 0; i < 8; ++i)
{
std::cout << i << endl;
}
}
int main () {
ofstream file;
file.open("example.txt");
if(file.is_open()){
std::cout << "File Open Access \n";
}
file << "Write this to the file";
addingtext();
//file << addingtext;
file.close();
return 0;
}
addingtext()
returns nothing, and writes to std::cout
.
You have two options:
Option 1: Make addingtext()
return a string, and then write that to the file:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
std::string addingtext() {
std::string result;
for (int i = 0; i < 8; ++i)
{
std::cout << i << endl;
result += i;
result += "\n";
}
return result;
}
int main() {
ofstream file;
file.open("example.txt");
if (file.is_open()) {
std::cout << "File Open Access \n";
}
file << "Write this to the file";
file << addingtext();
file.close();
return 0;
}
Option 2: Make addingtext()
write to the file:
#include <iostream>
#include <fstream>
using namespace std;
void addingtext(ofstream& o) {
for (int i = 0; i < 8; ++i)
{
std::cout << i << endl;
o << i << endl;
}
}
int main() {
ofstream file;
file.open("example.txt");
if (file.is_open()) {
std::cout << "File Open Access \n";
}
file << "Write this to the file";
addingtext(file);
file.close();
return 0;
}
Your function does not return any value.
If it returned a value, such as a string you have created during the running of the addingtext function you could then add that string straight to the file as you are doing there.
I think you want to pass the file stream to your function so it writes to the file instead of std out.
void addingtext(ofstream& stream){
for (int i = 0; i < 8; ++i)
{
stream << i << endl;
}
}
int main () {
ofstream file;
file.open("example.txt");
if(file.is_open()){
std::cout << "File Open Access \n";
}
file << "Write this to the file";
addingtext(file);
//file << addingtext;
file.close();
return 0;
}
If you want your function to return a string, don't declare it's return type as void. I would:
#include <string>
string addingtext(){
string temp;
for (int i = 0; i < 8; ++i)
{
temp += i;
}
return temp;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.