Read file from txt - c++

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.

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.

Getting input from a file C++ (Matrix Array Input)

I will have user input a file which will contain some data like this :
numRows
numCols
x x x ... x
x x x ... x
.
..
...
Now I am having trouble reading data from a file like this. I am not understanding what should I do to read each integer from each line. This is what I have so far:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class my_exception : public std::exception {
virtual const char *what() const throw() {
return "Exception occurred!!";
}
};
int main() {
cout << "Enter the directory of the file: " << endl;
string path;
cin >> path;
ifstream infile;
cout << "You entered: " << path << endl;
infile.open(path.c_str());
string x;
try
{
if (infile.fail()) {
throw my_exception();
}
string line;
while (!infile.eof())
{
getline(infile, line);
cout << line << endl;
}
}
catch (const exception& e)
{
cout << e.what() << endl;
}
system("pause");
return 0;
}
Also what I want is to store data at each line! That means after the first line I want to store data into the corresponding variable and each cell value.
I am confused as to how can I get each integer and store them in a unique(numRows and numCols) variable?
I want to save first two lines of the file into numRows and numCols respectively, then after each line's each integer will be a cell value of the matrix. Sample input :
2
2
1 2
3 4
TIA
Try this out. The first line reads in the path. Then, using freopen we associate the file provided with stdin. So now we can directly use cin operations as if we are directly reading from stdin and as if the input from the file is typed line for line into the console.
Following this, I create two variables corresponding to numRows and numCols and create a matrix of this dimension. Then I create a nested for loop to read in each value of the matrix.
string path;
cin >> path;
freopen(path.c_str(),"r",stdin);
int numRows, numCols;
cin >> numRows >> numCols;
int matrix[numRows][numCols];
for(int i = 0; i < numRows; i++){
for(int j = 0; j < numCols; j++){
cin >> matrix[i][j];
}
}
Alternatively you can use this to create your matrix
int** matrix = new int*[numRows];
for(int i = 0; i < numRows; i++)
matrix[i] = new int[numCols];
See this for more reference.

saving the results to a file within a for loop 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.

C++ pyramid of numbers

I need to write a program where it takes 2 integers from a file. Then it has to make a pyramid from those 2 numbers. It has to look like this:
I've wrote the code and it works as I want to, bet I can't think of a way how make it look a pyramid like.
Here's how it looks when I do it:
And this is my code:
#include <fstream>
using namespace std;
int main(){
ifstream inFile("Duomenys.txt");
ofstream outFile("Rezultatai.txt");
int N,M,smth,suma=0;
inFile >> N >> M;
smth=N;
while(N<=M){
for(int i=smth;i<=N;i++){
outFile<<i<<" ";
suma+=i;
if(i==N){
for(int i=N-1;i>=smth;i--){
outFile<<i<<" ";
suma+=i;
}
}
}
outFile<<endl;
N++;
}
outFile<<endl<<"Skaiciu suma: "<<suma;
inFile.close();
outFile.close();
return 0;
}
So my question would be, how to make it that my answer would be shaped in pyramid like in example?
#include <fstream>
#include <iostream>
#include <iomanip>
#include <assert.h>
using namespace std;
template <class T>
int numDigits(T number)
{
int digits = 0;
while (number) {
number /= 10;
digits++;
}
return digits;
}
int main()
{
ifstream inFile("Duomenys.txt");
ofstream outFile("Rezultatai.txt");
int N,M,smth,suma=0;
inFile >> N >> M;
smth=N;
// assuming positive numbers
assert(N>=0 && M>=0);
// this will be the size of each printed number
int nd = numDigits<int>(M)+1;
while(N<=M){
for(int i=N;i<=M;i++)
outFile << setw(nd) << " ";
for(int i=smth;i<=N;i++){
outFile << setw(nd) << i;
suma+=i;
if(i==N){
for(int i=N-1;i>=smth;i--){
outFile << setw(nd) << i;
suma+=i;
}
}
}
outFile<<endl;
N++;
}
outFile<<endl<<"Skaiciu suma: "<<suma;
inFile.close();
outFile.close();
return 0;
}
First you must compute your second number's digit count. It's so easy. Then you can calculate the depth of concluded pyramid using: (second number- first number)+1. After that you can be sure that in the last row, the max digit count you will have is ((second number - first number)*2+1)*digit count=x of pyramid's head. So you should print the head of pyramid at (x,y)=(x of pyramid's head, ....)
To determine the length of the last row you can either write your output to an std::stringstream and get the length with myStrStream.str().size() (and afterwards print the contents of your string stream to std::cout or your outFile) or you can count the length of all items of the last line separately and then sum then up, including spaces. I think the first approach is simpler.
The easiest approach might be backtracking.
This also depends on the digits that every number have.
Assuming that every number has two digits, is enough to add a certain number of space for each iteration.
This number in your case is 5 during the first iteration, and ends up being zero:
#include <fstream>
using namespace std;
int main(){
ifstream inFile("Duomenys.txt");
ofstream outFile("Rezultatai.txt");
int N,M,smth,suma=0;
inFile >> N >> M;
smth=N;
while(N<=M){
for(int i=smth;i<=N;i++){
outFile<<i<<" ";
suma+=i;
if(i==N){
for(int i=N;i<M;i++)
cout << " ";
for(int i=N-1;i>=smth;i--){
outFile<<i<<" ";
suma+=i;
}
}
}
outFile<<endl;
N++;
}
outFile<<endl<<"Skaiciu suma: "<<suma;
inFile.close();
outFile.close();
return 0;
}
An alternative is to use iomanip's setw, but this case you have to write all numbers in a string and print the whole string each time.
#include<fstream>
using namespace std;
ofstream outFile("output");
void printSpace(int a){
string spaces(a,' ');
outFile<<spaces;
}
int main(){
int N=1,M=11,smth=4,suma=0;
int l=2*(M-N);
while(N<=M){
printSpace(l);
for(int i=smth;i<=N;i++){
outFile<<i<<" ";
suma+=i;
if(i==N){
for(int i=N-1;i>=smth;i--){
outFile<<i<<" ";
suma+=i;
}
}
}
l-=2;
outFile<<endl;
N++;
}
outFile<<endl<<"Skaiciu suma: "<<suma;
outFile.close();
return 0;
}
inFile >> N >> M;
smth=N;
while(N<=M){
for(int position=0;position<(M-N);position++){ // doesn't work if M<N obviously
for(int digit=(smth+position);digit;digit=digit/10){
outFile<<" ";
}
outFile<<" "; // this is to complement the spacer for each digit in your code
}
for(int i=smth;i<=N;i++){
outFile<<i<<" ";
...

How to read a table from .txt file to C++

I want to read a matrix from a file and use it in my program. but when I output the results, it shows that it is not reading correctly.
Here is the code:
#define I 5
#define J 5
#define P 2
int i,j,k; //for loops
int main ()
{
ifstream inFile;
ofstream outFile;
double C[I][J];
inFile.open("C.txt", ios::in);
if (! inFile) {
cerr << "unable to open file C.txt for reading" << endl;
return 1;
}
for(i=0; i<I; i++)
for(j=0; j<J; j++)
inFile >> C[i][j];
outFile.open("results.txt");
outFile<< "C" <<endl;
for(i=0;i<I;i++)
{
for(j=0;j<J;j++)
outFile<< C[i][j];
outFile<< endl;
}
inFile.close();
outFile.close();
return 0;
}
C is a matrix of integer values 2 3 5... but what I get is
316-9.25596e+061-9.25596e+061-9.25596e+061-9.25596e+061
-9.25596e+061-9.25596e+061-9.25596e+061-9.25596e+061-9.25596e+061 -9.25596e+061-9.25596e+061-9.25596e+061-9.25596e+061-9.25596e+061 -9.25596e+061-9.25596e+061-9.25596e+061-9.25596e+061-9.25596e+061 -9.25596e+061-9.25596e+061-9.25596e+061-9.25596e+061-9.25596e+061
You should output a whitespace after each number, otherwise they will be all glued together.
outFile<< C[i][j] << " ";
You also should check your input for validity. Not showing it here (you already know how to check if (! inFile)).
I suspect that you are having problems with new lines, below modification will ignore new line character after reading each line:
for(i=0; i<I; i++) {
for(j=0; j<J; j++)
inFile >> C[i][j];
inFile.ignore(); /// <<<--------
}
It seems you are writing uninitialized variables to your output file, leading to undefined behavior.
I suspect your C.txt file does not contain the 5x5 matrix your program is looking for.
You should add a simple error check, e.g.:
for(i=0; i<I; i++)
for(j=0; j<J; j++)
if (!(inFile >> C[i][j])) { /* something's wrong here */ }