saving the results to a file within a for loop c++ - c++

I'm doing a lab in university that multiplies out 2 matrices from 2 different files and in one of the questions i've been asked to print the results on the console (which is not a problem, it's already done) but printing it to a new save file is the problem.
i'm fairly new to c++ so i apologize in advance if the mistake is obvious :(
here is my code so far....
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
///////// my output file /////////////
string outfile1, save;
cout<<"Please enter the name of the file you want to save the results in"<<endl;
cin>>outfile1;
ofstream outfile(outfile1.c_str());
if(!outfile)
{
cout<<"Please drag in the right file you want the results to be saved on"<<endl;
system("PAUSE");
return -1;
}
/////// sitting up the first matrix file ////////
string matrixA;
cout<< "Please drag file (matrix1) into this window"<<endl;
cin>>matrixA;
ifstream infile;
infile.open(matrixA.c_str());
if(!infile)
{
cout<<"ERROR: Wrong file, please try restart program and try again."<<endl;
return -1;
}
string matrix1;
int a[5][5];
for (int i = 0; i<5;i++)
{
for(int j = 0;j<5;j++)
{
getline(infile,matrix1,',');
a[i][j]= stoi(matrix1);
cout<< a[i][j]<<" ";
}
cout<<endl;
}
infile.close();
/////// sitting up the 2nd matrix file ////////
string matrixB;
cout<< "Please drag file (matrix2) into this window"<<endl;
cin>>matrixB;
ifstream infile2;
infile2.open(matrixB.c_str());
if(!infile2)
{
cout<<"ERROR: Wrong file, please try restart program and try again."<<endl;
return -1;
}
string matrix2;
int b[5][5];
for (int k = 0; k<5;k++)
{
for(int l = 0;l<5;l++)
{
getline(infile2,matrix2,',');
b[k][l]= stoi(matrix2);
cout<< b[k][l]<<" ";
}
cout<<endl;
}
infile2.close();
////////////// CALCULATIONS //////////////////////
cout<<"The product of both matrices is: "<<endl;
int result[5][5];
while (outfile1)
for (int x = 0; x < 5; x++)
{
for (int y = 0; y < 5; y++)
{
result[x][y] = 0;
for(int z = 0; z < 5; z++)
{
result[x][y] += a[x][z]*b[z][y];
}
cout << result[x][y] <<" ";
outfile1<< result[x][y]<<" "; // <<---------- why can i not do this?
}
cout<<endl;
}
system("PAUSE");
return 0;
}
is there an easier way to do it? if i try to run the code as it is, it gives me a highlight under the first "<<" saying (no operator "<<" matches these operands)
outfile1<<result[x][y]<<" ";

Your program doesn't compile because of two reasons.
while (outfile1)
outfile1 is an std::string (the output file name) and is not convertible to bool. It's not quite clear what you tried to achieve with this code.
outfile1<< result[x][y]<<" ";
Again, outfile1 is an std::string. Your output stream is outfile, so you should change this to
outfile << result[x][y] << " ";

outfile1 is of type string, while outfile is of type ofstream. Change outfile1 to be outfile on lines 86 and 100 and it should compile as expected.
You may want to name your variables differently to help prevent errors like this, perhaps naming outfile1 as outfileName.

Related

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.

no operator << matches these operands visual c++

I am having an error message that i cant figure out how ti get rid of. I am trying to have my program ask the user for the file name and then output a list of prime numbers from 1 - 100 to that file. I can get it to work if the file is an "ofstream outputfile;" that I specify but when I change it to an input file the error pops up. It is on line 28 right after inputFile. I have checked other questions on this and they all say to include the header which I have done but it still doesn't fix the issue. I am new to programming so I appreciate your help and patience.
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
bool isPrime(int);
int main()
{
ifstream inputFile;
string filename;
cout << "Enter a filename: ";
cin >> filename;
inputFile.open(filename);
for (int i = 1; i <= 100; i++)
{
isPrime(i);
while (isPrime(i) == true)
{
inputFile << i << endl; //ERROR IS HERE!
break;
}
}
inputFile.close();
system("pause");
return 0;
}
bool isPrime(int n)
{
bool isPrime = true;
for (int i = 2; i<n; i++)
{
double x = n%i;
if (x == 0.0)
isPrime = false;
}
return isPrime;
}
In C++ operator << is user for output to output streams (like std::ofstream), and operator >> is used for input streams (like std::ifstream).
So, replacing ifstream to ofstream will fix this.
If you want to write something in the file
Instead of declaring an ifstream object declare a ofstream object that will fix your problem

printing weird symbols to output file, c++

I am writing a code that reads an input file of numbers, sorts them in ascending order, and prints them to output. The only thing printed to output is some really freaky symbols.
Here is my code
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
int i, y, temp, num[20];
char file_nameI[21], file_nameO[21];
ofstream outfile;
ifstream infile;
cout << "Please enter name of input file: ";
cin >> file_nameI;
infile.open(file_nameI);
if (!infile)
{
cout << "Could not open input file \n";
return 0;
}
cout << "Please enter name of output file: ";
cin >> file_nameO;
outfile.open(file_nameO);
if (!outfile)
{
cout << "Could not open output file \n";
return 0;
}
for (i = 0; i < 20; i++)
{
y = i + 1;
while (y < 5)
{
if (num[i] > num[y]) //Correction3
{
infile >> temp;
temp = num[i];
num[i] = num[y];
num[y] = temp;
//y++; //Correction4
}
y++;
}
}
for (i = 0; i < 5; i++)
outfile << "num[i]:" << num[i] << "\n";
return 0;
}
Here is my input
6 7 9 0 40
Here is the output
 „Ô,üþ 54
H|À°ÀzY „Ô,üþ 0
Problems with your code are already mentioned in the comments but again:
First problem is uninitialized elements of num[20] - elements of num have indeterminate values so accessing any of them triggers undefined behavior. You should first read them from the file or at least initialize them to some default value.
The part of code that should most likely do the sorting is just completely wrong. If you'd like to implement your own function for sorting, you can pick up some well-known algorithm like e.g. quicksort - but C++ Standard Library already provides sorting function - std::sort.
Besides obvious mistakes:
You are using char[] - in C++ it's almost always better to use std::string.
Your static array can only store 20 values and you are reading those from a file. You can use std::vector which can grow when you add more elements than its current capacity. It also automatically fixes the problem with uninitialized elements of num[20].
As mentioned in the comments you can organize your code and improve readability by splitting it into functions.
Here you've got it quickly rewritten. This code uses std::string instead of char[], std::vector to store the numbers and std::sort. If there is something you don't understand here, read SO documentation:
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> read_file(ifstream& in_file)
{
vector<int> vec;
int value;
while (in_file >> value)
{
vec.push_back(value);
}
return vec;
}
void write_file(ofstream& out_file, const vector<int>& values)
{
for (size_t i = 0; i < values.size(); ++i)
out_file << "value #" << i << ": " << values[i] << '\n';
}
int main()
{
string input_filename, output_filename;
ofstream out_file;
ifstream in_file;
cout << "Please enter name of input file: ";
cin >> input_filename;
in_file.open(input_filename);
if (!in_file)
{
cout << "Could not open input file\n";
return 0;
}
cout << "Please enter name of output file: ";
cin >> output_filename;
out_file.open(output_filename);
if (!out_file)
{
cout << "Could not open output file\n";
return 0;
}
auto numbers = read_file(in_file);
sort(begin(numbers), end(numbers));
write_file(out_file, numbers);
return 0;
}
You might forgot to store values in num array. Just update your code as follows and it will work.
infile.open(file_nameI);
if (!infile){
cout << "Could not open input file \n";
return 0;
} else{
i = 0;
while (infile >> num[i]){
i++;
}
}

reading data file for root cern graphing

I created a script to take data from a text file and graph it in Root (CERN) but haven't used root in about a year, updated to the current version of Root and now it gets the error "Error: Function readprn() is not defined in current scope :0:
* Interpreter error recovered *" when i try to use it with Root.
It runs an excel data file that I saved as a txt file. The first column is the x value corresponding to each y value in the subsequent 768 columns. At the end it graphs and fits and loops over a couple graphs.
I'm mostly wondering if there is anything in the new versions that would cause this to not be able to be read by root.
#include <TGraph.h>
#include <TCanvas.h>
#include <TF1.h>
#include <TMath.h>
#include <TStyle.h>
#include <iostream>
#include <fstream>
#include <string>
using std::cout; using std::endl;
int threshold1(Int_t channel=0)
{
const char* ifname = "thresholdScanRun110FPGA4.txt";
cout<< "processing file " << ifname <<endl;
std::ifstream ifile(ifname);
if (!ifile) {
cout<< "Could not find file " << ifname <<endl;
return 0;
}
//std::string line;
// discard the first two lines
//std::getline(ifile, line);
//cout<< line <<endl;
//std::getline(ifile, line);
//cout<< line <<endl;
std::string str;
double number;
// read the first row (in sense of Exel's row)
ifile >> str;
//cout<< str <<endl;
for (int i=0; i<768; ++i) {
ifile >> number;
//cout<< number << " ";
}
//cout<<endl;
// read the second "row"
ifile >> str;
//cout<< str <<endl;
for (int i=0; i<768; ++i) {
ifile >> number;
//cout<< number << " ";
}
//cout<<endl;
double thres[60];
double prob[60][768];
int nthres_max = 60;
for (int ithres=0; ithres<nthres_max; ++ithres) {
ifile >> thres[ithres];
for (int iprob=0; iprob<768; ++iprob) ifile >> prob[ithres][iprob];
}
cout<< "The channel " << channel <<endl;
for (int ithres=0; ithres<60; ++ithres) {
cout<< thres[ithres] << " " << prob[ithres][channel] <<endl;
}
Double_t probability[60];
for (int ithres=0; ithres<60; ++ithres) probability[ithres] = prob[ithres][channel];
TGraph* gr = new TGraph(60, thres, probability);
gr->SetMarkerStyle(29);
gr->SetMarkerColor(4);
gr->SetTitle("Threshold Scan ChipX, ChanY");
TF1* ferfc = new TF1("ferfc", "0.5*TMath::Erfc((x-[0])/[1])", 0, 767);
ferfc->SetParameters(100,10);
new TCanvas;
gStyle->SetOptFit(1);
gr->Draw("apl");
gr->Fit("ferfc");
return 0;
}
int threshold_all()
{
for (Int_t channel=0; channel<2; ++channel) {
threshold1(channel);
}
}
when loading your macro in root 6.07/04, with .L macro.C I receive the following warning:
/tmp/tmp.rQTNVdlydv/macro.C:88:1: error: control reaches end of non-void function [-Werror,-Wreturn-type]
which is because you don't have a return statement in int threshold_all(). Fixing this the macro seems fine to me. (runs, opens a canvas, some fit output. Since I don't have your input values, I just created a text file with a few invented numbers and reduced the number of thresholds and values to 5x6. Which is why I'm not concerned about the abnormal fit termination which I receive.).
Also loading the macro with compilation .L macro.C+ looks fine to me once adding the return statement.

Read file from txt

I ve got a txt file with double matrix 50x8. The first two lines contains the array size
50
8
the 50x8 matrix. When i trid to read this file with the above code:
#include<iostream>
#include<fstream>
using namespace std;
int main() {
ifstream infile;
infile.open("C:/Users/zenitis/Desktop/BTHAI_2.3b-src/BTHAI/txtFiles/W1.txt");
double events[50][8];
while (!infile.eof())
{
for(int j=0;j<50;j++)
{
for(int k=0; k<8;k++)
{
infile >> events[j][k];
// infile.get(c
}
}
} //end while
infile.close();
for(int i = 0; i<50; i++){
for(int l=0; l<8; l++){
cout << events[i][l] << " ";
}
cout << "\n";
}
cout << events[0][0];
system("pause");
return 0;
}
Firstly when i print the results the first two elements of the events matrix are the last two of the file. Secondly any idea how to read just the two first elements which is in fact the size of the matrix????
You read the number of rows and columns like this:
int R, C;
infile >> R;
infile >> C;
You do it before the nested loops that read the rest of the file. Then you use the numbers from the file as your end-of-loop targets, rather than hard-coding 50 and 8.