I want to write data to a .txt
file, collected by a function from main.cpp
then passed via MyFunction.h
file, and make the record with MyFunction.cpp
file.
But I can't find a way to pass strings in float in one function. And even can't pass one string.
I'm just learning C at the moment, so please provide some advice.
CodePudding user response:
I suggest you look at those functions:
- std::to_string: convert a numerical value to a string
- std::stoi/std::stof: convert a string to a integral/floating point value
CodePudding user response:
First of all to pass data to a file you should understand how works the directive fstrem what should be included like
#include <fstream>
#include <cstdlib> // for exit function
First we should create the output stream and in my case a array, whom will be passed to the file.
int main()
{
ofstream outdata; // outdata is like cin
int i; // loop index
int num[5] = {4, 3, 6, 7, 12}; // list of output values
outdata.open("example.txt"); // opens the file
if( !outdata ) { // file couldn't be opened
cerr << "Error: file could not be opened" << endl;
exit(1);
}
for (i=0; i<5; i)
outdata << num[i] << endl;
outdata.close();
return 0;
}