How to display matrix file in rows and columns - c++

pardon my code formatting as I have just started out in C++.
Anyway, I am trying to read and display the contents (in the form of matrix) from a text file.
While I am able to read in the file, instead of displaying the outputs as how it should be as in its text file, I am getting the contents all in a single line. I can't brute force the code as I have several file where its matrix is different.
Eg. matrix01
9 7 6
8 -1 0
Or matrix02
2 10
3 5
-7 25
The following code is the my file input, and so what can I do to make it out in rows and columns instead of a single row/line?
#include <iostream>
#include <fstream>
using namespace std;
int main(){
ifstream fin; //file input stream
ofstream fout; //file output stream
fin.open("/Desktop/matrix_a.txt");
fout.open("/Desktop/matrix_a.out");
string msg;
while (fin>>msg){//read until eof
cout << msg << " ";
}
fin.close();
fout.close();
}

You state:
I am getting the contents all in a single line.
Your code does the following:
while (fin>>msg){//read until eof
cout << "" << msg << " ";
}
This is because you do not write a std::endl to std::cout, here, and you do not end up printing a newline at any time. operator<< does not automatically add a newline at the end of the statement. It is your responsibility to do, if so desired.

Related

C++ File Input/Output Console Output

My question is how can I get my console to properly display the contents of fileB based on the below information.
Below is the code I have created for basic file input/output operations. I am trying to copy the content from fileA over to fileB. After this is done I am trying to display the contents of fileB to cout. The code runs and updates the contents of fileB to whatever was stored in fileA. However, the console does not display the new content of fileB. It just shows a blank box.
#include <iostream> // Read from files
#include <fstream> // Read/Write to files
#include <string>
#include <iomanip>
void perror();
int main()
{
using std::cout;
using std::ios;
using std::ifstream;
ifstream ifile; // ifile = input file
ifile.open("fileA.txt", ios::in);
using std::ofstream;
ofstream ofile("fileB.txt", ios::out); // ios::app adds new content to the end of a file instead of overwriting existing data.; // ofile = output file
using std::fstream;
fstream file; // file open fore read/write operations.
if (!ifile.is_open()) //Checks to see if file stream did not opwn successfully.
{
cout << "File not found."; //File not found. Print out a error message.
}
else
{
ofile << ifile.rdbuf(); //This is where the magic happens. Writes content of ifile to ofile.
}
using std::string;
string word; //Creating a string to display contents of files.
// Open a file for read/write operations
file.open("fileB.txt");
// Viewing content of file in console. This is mainly for testing purposes.
while (file >> word)
{
cout << word << " ";
}
ifile.close();
ofile.close();
file.close();
getchar();
return 0; //Nothing can be after return 0 in int main. Anything afterwards will not be run.
}
fileA.txt
1
2
3
4
5
fileB.txt (file is initially a blank text document).
fileB.txt (after code runs)
1
2
3
4
5
ofile will have an internal buffer and if it isn't flushed and you only write a small amount of data (possibly as much as 64kb) then no data will be written to your output file until you call ofile.close() or at the end of main().
Simply move ofile.close() to before file.open("fileB.txt").
This happens because you haven't closed the oFile object before you open the FileB.
ofile.close();
file.open("fileB.txt");
By doing this you will have access to the updated file.
I hope that this helps you.

What is tellg() in file handling in c++ and how does it work?

I tried to access the next characters to be read from the file using tellg() and returns the position correctly if the file has one line of text.. But when the file has more than one line it gives me some abnormal values.. I am attaching my code and the output i got below..
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char temp;
ifstream ifile("C:\\Users\\admin\\Desktop\\hello.txt");
ifile>>noskipws;
while(ifile>>temp)
{
cout<<temp<<" "<<ifile.tellg()<<endl;
}
}
output:
H 3
e 4
l 5
l 6
o 7
8
W 9
o 10
r 11
l 12
d 13
. 14
. 15
16
! 17
! 18
! 19
File : Hello.txt contains 3 lines as given below..
Hello
World
!!!
Don't understand why it starts with 3 in the print statement which should instead start from 1.. when there are 2 lines it starts printing from 2..
can anyone explain me..?
As a matter of fact tellg() is not to return the offset of a byte in a stream, but a pos_type descriptor which is reusable by seekg(). It will match the byte offset if the file is binary, but it is not guaranteed in a text stream. (In a *ix it will match too, but in Windows there is no direct assignment.)
Open the file in binary mode, because seekg() is used with an offset. If the modification of the file happens between two runs of your program, you'll need to store positionEof in a file.
Note: In binary mode you could actually store positionEof in an integer, but I prefer using the explicite type as long as it is possible.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
streampos positionEof;
// Record original eof position.
ifstream instream("C:\\Users\\istvan\\Desktop\\hello.txt", ios::in | ios::binary);
if (instream.is_open()) {
instream.seekg(0, ios::end);
positionEof = instream.tellg(); // store the end-of-file position
instream.close();
}
else
cout << "Record eof position: file open error" << endl;
// Append something to the file to simulate the modification.
ofstream outstream("C:\\Users\\istvan\\Desktop\\hello.txt", ios::app);
if (outstream.is_open()) {
cout << "write" << endl;
outstream << "appended text";
outstream.close();
}
// Check what was appended.
instream.open("C:\\Users\\istvan\\Desktop\\hello.txt", ios::in | ios::binary);
if (instream.is_open()) {
instream.seekg(positionEof); // Set the read position to the previous eof
char c;
while ( instream.get(c))
cout << c;
instream.close();
}
else
cout << "Check modification: file open error!" << endl;
return 0;
}

How to print output in a file after a few empty lines

What I want to do here, is print the word "hello", first at the beginning, then skip some lines, then print it again in the file. The number of lines I need to skip is specified by the user. The file may or may not be empty, and if it's not empty, I don't want to change data on lines other than I need to print. If the file is empty, then it has to skip empty lines and still print after some lines.
Here is my code:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main(){
ifstream f1("temp.txt");
ofstream f2("temp.txt");
int r;
cout << "Enter number of lines to skip:" ;
cin >> r;
f2 << "hello";
string org = "";
while(--r){
getline(f1, org);
cout << "org: "<< endl;
}
int pos = f1.tellg();
cout << "pos: " << pos << endl;
f2.seekp(pos, f2.beg);
f2 << "hello";
}
The output I receive when I input r=3, for example, and the file is empty:
org:
org:
pos: -1
Also, the file remains empty. No output.
tellg() does not seem to work.
Anyone has any idea what to do here?
First of all, don't read and write to the same file. Files are opened in different modes so this won't work. But aside from that it is also better practice to parse your input, then operate on it in memory and write out the desired result. so open the file, read what is of interest (you can store a map with the lines that are interesting, or read the whole thing into memory) then do your operations on it, and write out the result.

Reading integers from a file returns incorrect output (ifstream)

In my attempt to make an automatic Sudoku solver in C++, the first step I need is to read the 9x9 grid from a file. Currently I just try to simply read the data, and display it as output, however the output is not correct. My code is as following:
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
// Initialize string for the lines to be read in
string line;
// Create the object to read the file "data.txt"
ifstream sudokuData("data.txt");
// Check if file opened properly
if (!sudokuData.good()) {
cout << "Couldn't open the file.\n";
}
// Read only if file exists
if ( sudokuData.is_open() ) {
cout << "Starting to read from file... \n";
// Read as long as there are lines in the file
while ( getline(sudokuData,line) ) {
cout << line << '<\n';
}
// Close file once done reading
sudokuData.close();
} else {
// If file cannot be read, inform the user
cout << "Unable to open file";
}
return 0;
}
Which from all I can find, is correct. The data file contains the numbers from 1 to 9 in each row, separated by a space. An example line would be:
1 2 3 4 5 6 7 8 9
But when I run the code, I get the following output:
Starting to read from file
153709 1 2 3 4 5 6 7 815370
RUN SUCCESSFUL (total time: 38ms)
What the heck am I doing wrong?
I'm using NetBeans 8.0 as IDE, if that is of any use...
There is a typo in your code. At line 27 you define a multi-byte char constant with '<\n'. Remove the < sign and it should work fine.

How do I output specific characters from a txt file to specific points?

First task of the tutorial and I'm already stumped,
Right, I'm supposed to write down 3 numbers into a text file, open that file up, output all 3 numbers and the average. Managed to get the first 2 parts done but I've hit a wall at the actual output part.
Here is the contents of the text file exactly as it appears within the file:
25
10
12
And here is the code I have so far:
#include <fstream>
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
// Create an ifstream input stream for reading of data from the file
ifstream inFile;
inFile.open("ProgrammingIsFun.txt");
// Create an ofstream output stream for writing data to a file
ofstream outFile;
outFile.open("Results.out");
cout << "The first integer is " << endl;
cout << "The second integer is " << endl;
cout << "The third integer is " << endl;
cout << "The average is " << endl;
// Close the files since we're done with them
outFile.close();
inFile.close();
system("Pause");
return 0;
}
From what I understand the contents of the txt file can only contain those 3 numbers and nothing else (I could be wrong though)
Any help would be much appreciated.
I'm guessing that the preferred C++ way of reading integers from files would be:
int first, second, third;
inFile >> first;
inFile >> second;
inFile >> third;
You can then analogously output using the << operator on outFile.