Not getting any output after reading in from file - c++

#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.

Related

Is there a way i can use a text file to operate a program to display the occurrence of numbers in C++?

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream ticket ("numbers.txt");
bool isCovered[99];
int number;
for (int i = 0; i < 99; i++)
isCovered[number] = false;
// Read each number and mark its corresponding element covered
ticket >> number;
while (number != 0)
{
isCovered[number - 1] = true;
ticket >> number;
}
// Check if all covered
bool allCovered = true; // Assumes all covered initially
for (int i = 0; i < 99; i++)
if (!isCovered[i])
{
allCovered = false; //Finds one number not covered
break;
}
return 0;
I know i may have confused you all with the last question i posted but this time i understand the concepts and have an even better question. How can i display the number of occurrences using a txt file in fstream while using C++? And how would i properly use my for and if loops for said problem, thanks?
Update: Got the numbers from the text file to display as well as numbers 1 - 99. But how do i code for the number of occurrences?
#include <fstream>
#include <string>
using namespace std;
int main()
{
int i;
// Open the text file in the system
ifstream infile;
infile.open("numbers.txt");
if(infile.fail())
{
cout << "This file does not work";
}
else{
string s;
while(infile >> s){
cout << s << endl;
}
}
// Display all numbers 1 through 99
for (i = 1; i < 99; i++){
cout << i << endl;
}
}

C++ while, for and array

Hey guys I stuck working on an assignment in which I asked to write a program that lists the contents of a file.
#include<iostream>
#include<fstream>
using namespace std;
int main() {
string array[5];
ifstream infile("file_names.txt");
int x=0;
while(infile>>array[x++]){
for(int i=0;i<=x;i++){
infile >> array[i];
cout << array[i] << endl;}}
}
basically I have a file named "file_names.txt" that contains three strings and I want my program to list them.
you don't need two loops.
int main() {
int array_size=5;
string array[array_size];
ifstream infile("file_names.txt");
int x=0;int i=0;
while(i<array_size && infile>>array[i]){ //order is important here
cout << array[i] << endl;
i++;
}
}
Your assignment was
an assignment in which I asked to write a program that lists the contents of a file.
One way of printing the contents of a file could be
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream fin("my_file.txt", ios::in); // open input stream
if(!fin){ // check state, that file could be successfully opened
printf("Error opening file.");
return 1;
}
while(fin.peek() != EOF){
cout << (char)fin.get();
}
fin.close(); // close input stream
return 0;
}
This code demonstrates some basic C++ functionality like
opening an input stream, checking the state of the input stream and reading the contents character by character. Try to understand each step.
I know I can get to the same result like this
string array[50];
ifstream infile("file_names.txt");
for(int i=0; **i<3**; i++){
infile >> array[i];
cout << array[i] <<endl;}
But the whole point is to use a while loop because there might be more or less than 3 items

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++ read from file failing - g++11 - Ubuntu14

sorry for having to ask such a trivial question here, but I have to admit I can't think the reason that's causing my program to behave this way.
Here's the problem;
I'm trying to read from a file which has 32 lines with each line containing a 32-bit long binary number.
I've got a string array of size 32 and I'm trying to store each number from the file in it. It seems straight forward to me but then when I get to the line that tests getline() it jumps to the else bit and ouputs my error message. Initially it was working fine on eclipse but not from the terminal, I thought it had something to do with the permissions so I changed them all to rwx to no avail. I even tried changing the name but that caused the program to not work even in eclipse and now even going back to the original name doesn't work !!
I would appreciate if anyone can shed a light on the problem for me.
Ta!
Edit: Thank you guys for helping me investigate the problem, so far the file seems to be read just fine, I've got a cout statement in my main function to print the second element of the vector in which data is stored (after being read from the file) and it prints fine, in eclipse that is!! .When I compile the same code from the terminal and then run a.out it simply doesn't output anything.
I decided I would include my entire code and hope this will be more helpful.
Here's a quick recap to the questions I was asked:
-The file is just a simple text file that contains lines of 1's and 0's here's what it looks like
00000000000000000000000000000000
11100000000000100000000000000000
00010000000000010000000000000000
10010000000001100000000000000000
10010000000000100000000000000000
10010000000001100000000000000000
00000000000001110000000000000000
10000000001000000000000000000000
10110110010000000000000000000000
00000000000000000000000000000000
I've got a cpp file with it's corresponding header like this:
#ifndef MANCHESTER_H_
#define MANCHESTER_H_
#include <string>
#include <iostream>
#include <fstream>
#include <cmath>
#include <vector>
using namespace std;
class Manchester {
private:
struct Processor
{
enum operation { JMP,JRP,LDN,STO,SUB,CMP,STP };
char accumulator[32]; // holds results of arithmetic operations.
char controlInstruction[32]; // program counter.holds the address of an instruction.
char presentInstruction[32]; //contains the actual instruction fetched and being executed.
};
Processor processor;
public:
vector<string> store;
int static const size = 32;
Manchester();
~Manchester();
void copyFromFileToStore();
string decToBinary(int );
int binToDecimal(string s);
string getInstruction(int lineNumber);
string getOperand(int lineNumber);
};
#endif /* MANCHESTER_H_ */
Here's the .cpp file
#include "Manchester.h"
Manchester::Manchester()
{
copyFromFileToStore(); // load the program in the store.
}
Manchester::~Manchester() {}
void Manchester::copyFromFileToStore()
{
ifstream myfile;
myfile.open("BabyTest1-MC.txt");
if (!myfile.is_open())
{
cout << "Cannot read file!" << endl;
}
else
{
int i =0;
while( i < 10)
{
string line;
if (getline(myfile,line))
{
store.push_back(line);
i++;
}
else
{
cout << "Error while reading file!" << endl; // always outputs when running the code.
return;
}
}
myfile.close();
}
}
string Manchester::decToBinary(int number)
{
string converted="";
char holder;
do
{
holder = number % 2 + '0';
converted = holder + converted;
number = number /2;
}while (number != 0);
string filler = "";
int stringsize = converted.size();
int diff = (8 - stringsize);
if (diff > 0)
{
for (int i = 0; i < diff; i++)
filler = filler + '0';
}
converted = filler + converted;
return converted;
}
int Manchester::binToDecimal(string s)
{
int converted =0;
int power = 0;
for (int i = s.size()-1; i >= 0; --i)
{
converted += (s[i] - '0') * pow(2, power);
power++;
}
return converted;
}
And finally the file containing the main():
#include "Manchester.h"
int main()
{
Manchester baby;
cout << baby.store.at(1);
return 0;
}
These the original parts that I posted that I didn't want to delete:
string store[32];
ifstream myfile;
myfile.open("BabyTest1-MC.txt");
if (!myfile.is_open())
{
cout << "Cannot read file!" << endl;
}
else
{
int i =0;
while( i < 32)
{
if (getline(myfile,store[i]))
{
i++;
}
else
{
cout << "Error while reading file!" << endl; // always outputs when running the code.
return;
}
}
myfile.close();
}
Sorry I'm editing to show you what works on eclipse but not from the terminal!!!
I simply don't understand the behaviour !!!
string store[32];
ifstream myfile;
myfile.open("BabyTest1-MC.txt");
if (!myfile.is_open())
{
cout << "Cannot read file!" << endl;
}
else
{
int i =0;
while( i < 32)
{
getline(myfile,store[i]);
i++;
}
myfile.close();
}
Why don't you use a std::vector<std::string>, and push_back() to populate it?
std::vector<std::string> store;
// ...
while(i < 32) {
std::string line;
if (getline(myfile,line)) {
store.push_back(line);
i++;
}
// ...
}
What about:
string store[32];
ifstream myfile;
int i;
myfile.open("filename.txt");
if (!myfile.is_open())
{
cout << "Cannot read file!" << endl;
}
else
{
for (i = 0; i < 32; i++)
{
if (!getline(myfile, store[i]))
{
cout << "Error while reading file!" << endl; // always outputs when running the code.
return 0;
}
}
myfile.close();
}
Tested it and it was working for me.
This way the for loop automatically increment you variable and if for some strange reason the program reaches the end of the file, it will display your error message.
I got some help from one of the guys at university and we figured what the problem was !!
It was to do with the endline characters. I'm working on linux which uses \n as the endline character but the file I'm trying to read was built on Windows which of course has \r\n as the endline character! Eclipse seems to be accepting both versions of end of line but not bash!
I edited my code to get rid of those characters altogether before storing them in the vector and it now works fine.
Sorry for the trouble caused in here and hope this will at least remind beginners that there is a difference between files built on windows, mac and linux !! and that attention needs to be made when working with different files !!
void Manchester::copyFromFileToStore()
{
ifstream myfile;
myfile.open("BabyTest1-MC.txt");
if (!myfile.is_open())
{
cout << "Cannot read file!" << endl;
}
else
{
int i =0;
string line;
while(getline(myfile,line))
{
line.erase(std::remove(line.begin(), line.end(), '\r'), line.end());
line.erase(std::remove(line.begin(), line.end(), '\n'), line.end());
store.push_back(line);
i++;
}
myfile.close();
}
}

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.