ofstream inconsistently creates/writes output file C++ - c++

I'm working with visual studio 2013. I want to output a vector of objects into several files. I am able to create the output file if I just print everything to a single file, but if I try to output to multiple files, nothing happens.
#include<vector>
#include<fstream>
#include<iostream>
#include<string>
using namespace std;
struct object
{
int a, b;
};
int main()
{
vector<object> DATA;
//fill DATA
ofstream out; string outname;
outname = "TL" + ".txt";
out.open(outname.c_str());
for (int i = 0; i < p; i++)
{
for (int k = 0; k < DATA.size(); k++)
{
out << i << endl;
if (DATA[k].a == i)
out << DATA[k].b << endl;
}
out << endl;
}
out.close();
return 0;
}
The above works exactly as I expect. However, if I rearrange it so that I could make separate files:
for (int i = 0; i < p; i++)
{
ofstream out; string outname;
outname = "TLR" + to_string(i) + ".txt";
out.open(outname.c_str());
for (int k = 0; k < DATA.size(); k++)
{
if (DATA[k].a == i)
out << DATA[k].b << endl;
}
out.close();
}
I get no output. I already checked to see if the files were being created in another directory and nada. Placing "cout << out.is_open()" after each of the cases shows that the single file is actually being opened (output 1), while the multiple files are not being opened (output 0).
Could anyone tell me what's going on and what can I do to fix this? I don't want to have to run the program and then open the output file to parse after I've made it.
Thank you.

When I was making the multiple files, I used the pipe, "|", (not shown) in the filename--which is a forbidden character in Windows' filenames.

Related

How to save looped output in C++ to a .txt file with columns and rows

I'm a C++ newbie and am wanting to save outputs that are printed when looping over several files. The outputs are 3 floats, which are called mass_pole, sum, and sum_SM. How do I save these looped outputs (without overwriting them) to a .txt file using the proper C++ tabs / new line semantics. I'm wanting something like:
//mass_pole //sum //sum_SM
200 2300.2 713.4
250 2517.3 1231.77
300 2110.5 432.5
inside a .txt file (without the headers).
My code so far is below, but I don't think this is correct for my aforementioned desire. Specifically, I need help with L25 onward. Any advice would be much appreciated!
// root -l aTGCs_test.C
#include <iostream>
#include <fstream>
#include <string>
#include "TMath.h"
using namespace std;
void masspoleweights(TString file, TString mass_pole) {
TChain* myTrees = new TChain("Events");
[. . .]
for (int j = 0; j < myTrees->GetEntries(); ++j){
//for (int j = 0; j < 1000; ++j){
myTrees->GetEntry(j);
sum=variable1;
sum_SM=variable2;
}
L25>> ofstream myfile ("weights.txt");
//saving outputs to file (three outputs that loop by mass: mass, sum, pdfweights)
for (int i = 0; i < 200; ++i){
myfile << mass_pole << sum << sum_SM << std::endl;
}
}
As per the help of all the experts in the comments section, here is the final code that works:
ofstream myfile ("weights.txt", ios::in | ios::out | ios::app); //file open mode (READ), WRITE, append
//loop over all outputs to save in a txt file (no overwrites):
for (int i = 0; i < 1; ++i){
ofstream::ios_base::app;
myfile << mass_pole << "\t" << sum << "\t" << sum_SM << "\n";
}

Read csv file using 2d array

I'm trying to read a CSV file using 2d array but there's a problem with the reading. The first cell of the file is skipped and then continues read all. I don't understand why it doesn't read the first cell.
#include<iostream>
#include<fstream>
#include<cstring>
#include<string>
#include<sstream>
using namespace std;
int main()
{
string arrival,job[3][4];
ifstream jobfile("myfile.csv");
std::string fileCommand;
if(jobfile.is_open())
{
cout << "Successfully open file"<<endl;
while(getline(jobfile,arrival,','))
{
for(int i=1;i < 4;i++) //i = no. of job
{
for(int j=0; j<4; j++) // j = no. of processes
{
getline(jobfile,job[i][j],',');
cout << "Job[" << i << "]P[" << j << "]: "<< job[i][j]<< endl;
}
}//end for
}//end while
}//end if for jobfile open
jobfile.close();
}
Change this:
for(int i=1;i < 3;i++)
to this:
for(int i=0;i < 3;i++)
Also, remove this getline(jobfile,job[i][j],',');, since you skip a line that way. When you called getline in the condition of the while loop, it already read a line (as a result, now, you have to store that line. Then, when the condition of the while loop is evaluated again, the next line will be read).
However, it gets much more complicated than this, since you arrival will hold one token at a time, until it meets the last token of the current line. In that case, arrival will be this: "currentLineLastToken\nnextLineFirstToken".
For that reason, you need to specially handle the case that arrival contains a newline, use string::find for this.
When a newline is found, you should split that string to that newline, in order to extract the two tokens involved. Use string::substr for this.
Moreover, you shouldn't loop inside the while loop with a double for to store the token, you just read. Use a double for loop, when it is time to print job, only after exiting the while loop that read the file.
Putting everything together, we get this:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string arrival,job[3][4];
ifstream jobfile("myfile.csv");
std::string fileCommand;
if(jobfile.is_open())
{
cout << "Successfully open file"<<endl;
int i = 0, j = 0;
while(getline(jobfile,arrival,','))
{
//cout << "|" << arrival << "|" << endl;
size_t found = arrival.find("\n");
if (found != std::string::npos) // if newline was found
{
string lastToken = arrival.substr(0, found);
string nextLineFirstTOken = arrival.substr(found + 1);
job[i++][j] = lastToken;
j = 0;
if(nextLineFirstTOken != "\n") // when you read the last token of the last line
job[i][j++] = nextLineFirstTOken;
}
else
{
job[i][j++] = arrival;
}
}//end while
for(int i = 0; i < 3; ++i)
{
for(int j = 0; j < 4; ++j)
{
cout << job[i][j] << " ";
}
cout << endl;
}
}//end if for jobfile open
jobfile.close();
}
Output (for my custom input):
Successfully open file
aa bb cc dd
bla blu blo ble
qq ww ee rr

Not getting any output after reading in from file

#include<iostream>
#include<cmath>
#include<fstream>
using namespace std;
int main()
{
int length [48];
int us[48];
int russ[38];
ifstream infile;
infile.open("data.txt");
if(infile.fail())
{
cout << "error" << endl;
return 1;
}
for(int i=0;i<48;i++)
{
infile >> length[i];
infile >> us[i];
while(i<=38)
{
infile>> russ[i];
}
infile.close();
}
for (int i = 0; i < 48; i++)
{
cout << length[i];
}
return 0;
}
I am trying to read each column above from a text file into a corresponding array. First column is length, second is us, third is russ. When i try to do a sample output to test it nothing is coming out. The program is compiling completely without bugs or errors but it is just not displaying the output.
Your problem is here
while(i<=38)
{
infile>> russ[i];
}
simply replace it with this:
while(i<38)
{
infile>> russ[i++];
}
Also, I don't know what you're trying to do exactly, since you're producing your output after too many for loops, therefore you're losing your data.

How to use fstream, to write different values in a .txt file

The problem I am facing is the following:
if we define something like
ofstream myFile;
myFile.open("Directory//debug.txt");
for (int i = 0; i < 10; i++)
{
myFile << i << endl;
myFile.close();
}
the output in the debug file will be 9.
I want to make it so that it outputs all the numbers from 0 to 9. Aside from closing the file after the for statement is it possible to define an ofstream that would do that?
No. You have two options:
Close the file outside the loop:
myFile.open("Directory//debug.txt");
for (int i = 0; i < 10; i++)
{
myFile << i << endl;
}
myFile.close();
or open the file in append mode and close inside the loop:
for (int i = 0; i < 10; i++)
{
myFile.open("Directory//debug.txt", ios_base::app);
myFile << i << endl;
myFile.close();
}
myFile.close();
should be put after the for-loop. Also introduce some error checking to see if the open was indeed a success.
I am calling a function foo repeatedly in a function goo I create the
file in foo and I want to output a new value each time foo is called
in goo.
In order to achieve your objective you could use a static variable inside foo
void foo()
{
static int count=0;
ofstream myfile;
myfile.open("Directory//debug.txt",std::fstream::app)
if (myfile.is_open()) // Checking is file is successfully opened.
{
count++;
myfile<<count<<"\n";
}
myfile.close; // Close the file
}

Reading integers from .dat file and collecting them in a vector

I am trying to read integers located in a dat file. I thought that this is the correct way to approach this problem but nothing prints out to the console and when I try to print out an index from vector nothing shows up indicating that nothing is actually being store in the vector. I would appreciate any help. Thank you!
vector<int> nums;
ifstream myfile;
myfile.open("nums.dat");
int a = 0;
while (myfile >> a) {
nums.push_back(a);
}
for (int i = 0; i < nums.size(); i++) {
cout << nums.at(i) << endl;
}
return 0;