How to write to file in separate function - c++

I am trying to get my program to write in a separate function than the main function, and I'm having a good deal of trouble. Here is a simplified version of my program:
#include <iostream>
#include <fstream>
using namespace std;
void writeToFile(int x)
{
outputFile << x << endl;
}
int main()
{
ofstream outputFile;
outputFile.open("program3data.txt");
for (int i = 0; i < 10; i++)
{
writeToFile(i);
}
outputFile.close();
return 0;
}

Your writeToFile function is trying to use the outputFile variable which is in a different scope. You can pass the output stream to the function and that should work.
#include <iostream>
#include <fstream>
using namespace std;
void writeToFile(ofstream &outputFile, int x)
{
outputFile << x << endl;
}
int main()
{
ofstream outputFile;
outputFile.open("program3data.txt");
for (int i = 0; i < 10; i++)
{
writeToFile(outputFile, i);
}
outputFile.close();
return 0;
}

You need to make your sub-function aware of outputFile. As written, that variable only exists inside of the 'main' function. You can change your function signature to:
void writeToFile(int x, ofstream of)
and call it like:
writeToFile(i, outputFile);
This will pass the variable to the sub-function so that it can be used in that scope as well.

Related

How often should one open/close fstream object c++

so the write elm and getfileID functions require the cursor pos in the file
(write elm appends to the end, getFileID prints lines first to last)
#ifndef file_operations_header
#define file_operations_header
#include <string>
#include <iostream>
#include <vector>
#include <fstream>
#include "First_classes_header.h"
class fileOPerations
{
private:
string line;
fstream f_myFileOut;
public:
fileOPerations();
void closeFile()
{
f_myFileOut.close();
}
int getFileID()
{
int counter = 0;
if (f_myFileOut.is_open())
{
while(f_myFileOut.good()){
getline(f_myFileOut,line);
++counter;
cout << line << endl;
}
}f_myFileOut.close();
return counter;
}
int writeElm(makeVector& mV,int i)
{
f_myFileOut.open("file.txt",ios::out|ios::app|ios::ate);
if (f_myFileOut.is_open())
{
f_myFileOut << mV.str_vector[i].counter << "\t";
f_myFileOut << mV.str_vector[i].name << endl;
}
else{
cout << "can't open file." << endl;
}
return 0;
}
friend class makeVector;
};
fileOPerations::fileOPerations():f_myFileOut("file.txt",ios::out|ios::app|ios::in){}
#endif // file_operations_header
and the call to getFileID in my main doesn't print anything because writeElm()
set the cursor pos to the end of the file.
#include <iostream>
#include <string.h>
#include <vector>
#include "First_classes_header.h"
#include "file_operations.h"
using namespace std;
int main()
{
fileOPerations fpObject;
makeVector vecObject;
int fileID = fpObject.getFileID();
while(true){
IDgenerator();
int genID = IDgenerator::GetID();
int currentID = fileID + genID;
string workingName = nameGetter::setName();
vecObject.vecSetter(currentID,workingName);
fpObject.writeElm(vecObject, currentID); // error within this function
fpObject.getFileID();
}fpObject.closeFile();
return 0;
}
Is it safe/effecient/effective to call f_myFileOut.open() with different parameters
in each separate function?
int getFileID()
{
f_myFileOut.open(("file.txt",ios::out|ios::app|ios::in)
int counter = 0;
...
...
int writeElm(makeVector& mV,int i)
{
f_myFileOut.open("file.txt",ios::out|ios::app|ios::ate);
Or should I set the cursor pos manually?
While it is certainly not efficient, to open/close the same file over and over again, it would be safe, and I'd even call it better coding style, because currently you are opening a file in one method and closing it in another, and in both cases it is not obvious from the function name that this is one of their side effects (contratry to e.g. closeFile()). Also you are already opening/closing the file in every iteration, so this would "only" double the open/close operations.
In general however, I'd definitively recommend to open the file once at the beginning of your program, close it at the end and e.g. use f_myFileOut.seekg (0,f_myFileOut.beg) and f_myFileOut.seekg (0,f_myFileOut.end) in between, to move your iterator around.

std::vector passed by reference is not passing from a function to main()

This question is very similar to some other questions that have been posted on here, but nonetheless, it does not seem to work when I implement previously suggested solutions. I am writing what should be some simple software that can be used to read in one column or multiple columns of data from a .txt file in a function and pass it to the main program for further calculations. The function call passes the file name to the function and reads in the data. Since this version only reads in one columns of data I could use a return function for this specific example, but I plan on expanding this to read in multiple columns of data so that is why I am using a void function. The column of test data is shown below.
103.816
43.984
2214.5
321.5
615.8
8.186
37.6
The for loop in the function Read_File reads back the data from the file perfectly indicating that the function works fine and properly reads in the data. However, when I try to display the same data using the same for loop in the main program i get an EXEC_BAD_ACCESS fault. To be clear the program compiles fine, but it is not passing the data to the main program, which indicates a pointer problem. Where am I going wrong with this? Any help would be greatly appreciated.
#include <vector>
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <iterator>
class Read_Columnar_File {
public:
void Read_File(const std::string& file_name,std::vector<float>& Column1);
};
#include <iostream>
int main(int argc, const char * argv[]) {
int i;
std::vector<float> Column2;
Read_Columnar_File File1;
char str[20];
std::strcpy(str,"Test.txt");
File1.Read_File(str,Column2);
std::cout << std::endl;
for(i = 0; i < 7; i++) std::cout << Column2[i];
}
void Read_Columnar_File::Read_File(const std::string& file_name,std::vector<float>& Column1)
{
int i;
std::ifstream inp(file_name,std::ios::in | std::ios::binary);
if(inp.is_open()) {
std::istream_iterator<float> start((inp)), end;
std::vector<float> Column1(start,end);
for(i=0; i < 7; i++) std::cout << Column1[i] << std::endl;
}
else std::cout << "Cannot Open " << file_name << std::endl;
inp.close();
}
you are declaring a local variable std::vector<float> Column1(start,end); inside the function
the local variable is being assigned the values, so actual vector is not updated.
This will fix the issue. column1 is locally declared.
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
class Read_Columnar_File {
public:
void Read_File(const std::string& file_name, std::vector<float>& Column1);
};
int main(int argc, const char * argv[]) {
int i;
std::vector<float> Column2;
Read_Columnar_File File1;
char str[20];
std::strcpy(str, "Test.txt");
File1.Read_File(str, Column2);
std::cout << std::endl;
for (i = 0; i < 7; i++) std::cout << Column2[i];
}
void Read_Columnar_File::Read_File(const std::string& file_name, std::vector<float>& Column1)
{
int i;
std::ifstream inp(file_name, std::ios::in | std::ios::binary);
if (inp.is_open()) {
std::istream_iterator<float> start((inp)), end;
Column1.assign(start, end);
for (i = 0; i < 7; i++) std::cout << Column1[i] << std::endl;
}
else std::cout << "Cannot Open " << file_name << std::endl;
inp.close();
}

Read Files using a function C++

I'd like to know how to read a file using streams but also using them inside a function.
So far my code is;:
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;
void burbuja(int[]);
void imprimeArreglo (int[],int);
void leeArchivo(string&);
int arreglo[10];
int i;
void burbuja (int a[])
{
int i,j;
for(i=0;i<10;i++)
{
for(j=0;j<i;j++)
{
if(a[i]>a[j])
{
int temp=a[i]; //swap
a[i]=a[j];
a[j]=temp;
}
}
}
}
void imprimeArreglo(int a[],int tam)
{
for(int i=0;i<tam;i++)
cout << a[i] << " ";
}
void leeArchivo(string& nombre)
{
string filename = nombre;
ifstream myfile(filename);
string line;
if (myfile.is_open()) {
while ( getline (myfile,line) )
{
cout << line << '\n';
}
myfile.close();
}
else cout << "Unable to open file";
}
int main()
{
string nombre = "arr.txt";
leeArchivo(nombre);
cin >> i ;
return 0;
}
I'd like to be able to call leeArchivo("arr.txt") from the main method.
With this I get the errors:
Error: bubble.cpp(37,14):'ifstream' is not a member of 'std'
Error: bubble.cpp(37,19):Statement missing ;
Error: bubble.cpp(39,20):Undefined symbol 'file'
Error: bubble.cpp(39,25):Could not find a match for 'std::getline(undefined,std::basic_string<char,std::string_char_traits<char>,std::allocator<char>>)'
What am I missing here? (I'm new to C++)
The file I'm trying to read has the following structure:
<number>
<number> <number> <number> ...
E.G.:
5
19 28 33 0 1
=========================================
EDIT:
I'm using Borland C++ 5.02
EDIT 2:
Updated code, using Geany Now error is: BUBBLE.cpp:38:25: error: no matching function for call to 'std::basic_ifstream<char>::basic_ifstream(std::string&)'
That's particularly odd behavior with ifstream. Try this edit:
void leeArchivo(const string&);
void leeArchivo(const string& nombre)
{
ifstream file(nombre.c_str());
string line;
while(getline(file,line)) {
cout << line << endl;
}
}
int main()
{
leeArchivo("arr.txt");
return 0;
}
Also, use:
#include <cstdlib>
Instead of:
#include <stdlib.h>

Problems with fstream

I'm writing a vector array to an ofstream file, however certain values aren't getting written, I.E.:
#include <iostream>
#include <vector>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
int main (){
char * hold = new char [100];
vector<double> fx(2049);
ifstream inputFile;
ofstream myFile;
inputFile.open("data.txt");
myFile.open("test.txt");
for (int c=0; c<2049; c++){
inputFile.getline(hold, 100);
fx[c] = atof(hold);
}
for (int c=0; c<2049; c++){
myFile << fx[c] << "\n";
}
}
Within fx, the second half is all equal to 0. (fx[1024] through fx[2048]==0). Within test.txt however, none of these 0 values are present, on the carriage return is applied. Any thoughts?
Thanks! (New to the formatting of these questions... any tips to make this more understandable would be appreciated.)
Note: I realize this program is rather redundant. The actual program has a great deal more functionality to it, this is just an area that is working incorrectly.
Try this
#include <iostream>
#include <vector>
#include <fstream>
#include <string>
#include <cstdlib>
#define MAX_FILE_LINES 2048
using namespace std;
//genarate random double number
double fRand()
{
double fMin = 100, fMax = 200;
double f = (double)rand();
return fMin + (f / (fMax - fMin));
}
//init file (if you need to create sample file with list of double numbers, you can use this function)
void fileInit(){
ofstream sourceFile;
sourceFile.open("D:\\source.txt");
if (sourceFile.is_open())
{
for (int i=0; i<MAX_FILE_LINES; i++){
sourceFile << fRand() << endl;
}
}
}
int main (){
string buffer;
vector<double> fx(MAX_FILE_LINES);
ifstream sourceFile;
ofstream destinationFile;
sourceFile.open("D:\\source.txt");
destinationFile.open("D:\\destination.txt");
//reading file lines to vector
int lineCount =0;
if (sourceFile.is_open())
{
while ( sourceFile.good() )
{
getline (sourceFile,buffer);
fx[lineCount] = atof(buffer.c_str());
lineCount++;
if (lineCount == (MAX_FILE_LINES-1)){
break;
}
}
sourceFile.close();
}
//write lines to new file
if (destinationFile.is_open())
{
for (int i=0; i<MAX_FILE_LINES; i++){
destinationFile << fx[i] << endl;
}
}
}
Why screw with handroll buffers for one-offs? You can't save a millionth of what it costs to think about cycles here, there's not enough waste to recoup.
Think about eliminating needless statements and unchecked failures first.
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
int main()
{
vector<float> data;
{
ifstream ids("source.txt",ios_base::in);
int linenr = 0;
for ( string line ; getline(ids,line) ; ) {
++linenr;
decltype(data)::value_type x;
istringstream s(line);
if ( s >> x )
data.push_back(x);
else
cerr << "crap line "<<linenr<<" ignored: " << line << '\n';
}
}
ofstream ods("object.txt");
for ( auto x : data )
ods << x << '\n';
}

How to write a series of float from text using fstream

Example ABC.txt
10.f 30.2f 20.f
I want to retrieve those information and store inside my array. However i am unsure how to do it.
I dont understand what is
Then (if good), it calls num_get::get (using the stream's selected locale) to perform both the extraction and the parsing operations, adjusting the stream's internal state flags accordingly. Finally, it destroys the sentry object before returning.
std::fstream filestr("ABC.txt", std::fstream::in);
if(!filestr.good()) //Logical error on i/o operation
{
//Unable to process
filestr.close();
return;
}
unsigned index= 0;
unsigned count= 0;
while(filestr.good())
{
float buffer= 0.f;
filestr >> std::skipws >> buffer;
score[index]= buffer;
++index;
}
filestr.close();
There are a number of ways to do this. One way is using stringstreams, in combination with vectors and strings:
#include <fstream>
#include <iostream>
#include <string>
#include <cstdlib>
#include <sstream>
#include <vector>
using namespace std;
int main() {
std::ifstream filestr("C:\\nums.txt", std::fstream::in);
std::vector<double> numbers;
if (!(filestr.good())) {
std::cout << "BAD FILE" << std::endl;
exit(0);
}
else {
std::string temp;
double d = 0.0;
while(std::getline(filestr, temp)) {
std::istringstream iss(temp);
while(std::getline(iss, temp, ' ')) {
std::istringstream ist(temp);
ist >> f;
numbers.push_back(f);
}
}
}
//see that the vector has information in it
for (int i = 0; i < numbers.size(); i++) {
std::cout << numbers[i] << std::endl;
}
filestr.close();
return 0;
}
One thing to note is that you could also use iterators here, but that's something you could implement for yourself.
Super simple with istream_iterator. There is only one tricky bit in the code below. The vector constructor call needs an extra set of parens around the first argument to avoid the Most Vexing Parse.
#include <fstream>
#include <iostream>
#include <iterator>
#include <vector>
#include <algorithm>
using namespace std;
int
main (int argc, char** argv)
{
for (int i = 1; i < argc; ++i) {
ifstream in (argv[i]);
if (!in) {
cerr << "Failed to open " << argv[i] << endl;
continue;
}
vector<double> nums ((istream_iterator<double> (in)), istream_iterator<double> ());
copy (nums.begin (), nums.end (), ostream_iterator<double> (cout, "\n"));
}
return 0;
}