Read a file in by columns in C++ - c++

I have a file that contains numbers:
23 899 234 12
12 366 100 14
10 256 500 23
14 888 564 30
How can I read this file by column using C++? I searched YouTube but they only read file by row. If I have to find the highest value from the first column, I need to read it by columns right?

Try initialising a variable called column =0
Now when you access row iterate through column using a for loop until end of column which can be found out by no of lines in a file, then implement the operation what you are willing to do, now increase column no for going to next column.
And you can get value in form of n*vectors
Where n is no of rows
Dimension of vector is length of column

Files are storages with sequential access, so , generally you have to read everything. Essentially it's like reading from a tape. And format of your file doesn't offer any shortcuts.
But, you can fast-forward and rewind along file, using seek() if it's a file on permanent storage. It's not effective and you have to know position where to go. If your records are of same size, you can advance by fixed amount of bytes.
That is usually done with binary formats and those formats are designed to have some kind directory or other auxiliary data to help searching for proper position..

Read each line and split it by space and store the first value as highest value. repeat the steps for all rows until you reach end of file while comparing the first value again with already stored value as highest.
I don't have C++ compiler available with myself to test. it should work for you conceptually.
#include <fstream>
#include <string>
#include <iostream>
#include<sstream>
using namespace std;
int main() {
ifstream inFile("Read.txt");
string line;
int greatest = 0;
while (getline(inFile, line)) {
stringstream ss(line);
string FirstColumn;
while (ss >> FirstColumn) {
if (stoi(FirstColumn) > greatest)
greatest = stoi(FirstColumn);
}
cout << greatest << endl;
}
}

Related

How to get line of numbers from file and ignore first number?

So, lets say we have a text.txt file with these numbers:
4 5 15 10 20
5 5 15 10 20 25
In the above example, the first numbers in the row describe how many numbers are in that row. The rest of the numbers are the numbers I am interested in (I will be sorting them in a later part of the code, but that is not where my question focuses).
My issue is, how can I best go about taking each row of numbers (ignoring the first number), placing them into a array, and then moving onto the next line and doing the same thing (placing them into an array, that will be later sorted)?
All my google searching points to doing this with strings via getline, and nothing really points to handling it with ints. Hope someone on here can help point me in the right direction.
Below is the basic code I would use to open the file:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int a;
ifstream inputfile;
//declare an input file
inputfile.open("text.txt");
while(//not sure best way to do this part)
{
//guessing I can use a for loop and place numbers in array
//based on first number in the row of numbers
}
return 0;
}
The most obvious way would probably be to read a line with std::getline, then put the string into a stringstream, and read numbers from there (ignoring the first, obviously).
I suggest the following approach:
std::string line;
// Keep reading lines of text from the file.
// Break out of the loop when there are no more lines in the file.
while (getline(inputfile, line)){
// Construct a istingstream from the line of text.
std::istringstream ss(line);
// Read the numbers from the istingstream.
// Process the numbers as you please.
}

How to find out how many strings are written into a binary file?

I have a binary file text.bin. The text inside is written this way:
4helo5hello6helloo. If I was not to know there are 3 strings inside,
how would I find out? I want to make a dynamic array of strings from a
binary file, but first I have to know how many strings there are in the file.
I know I can read it like this:
ifstream dat("text.bin", ios_base::binary);
if (!dat)
{
cout << "Error";
return 1;
}
int temporary;
dat.read((char*)(&temporary), sizeof(temporary));
char *arrray = new char[temporary];
dat.read(arrray, temporary);
string word = string(arrray, temporary);
How would I make this into a loop, so that it reads as long as there is something to read in the binary file? How would I find out how many words there are, so that I could prepare a dynamic array for the words? I am using:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
Keep it simple. If the binary format is like you said : 4helo5hello6helloo for example, do the following;
Read the first number,
substring from the position of the first number to however long the string is (the number you read),
Put the substring into a two-dimensional array (one dimension for the number of strings, the other for the length of the strings),
Wash rinse repeat until you reach the end of the file.
The length of the first dimension of the array is the number of strings in the file. The array now contains all the strings in the read file.
Cheers!
For 4helo5hello6helloo, write a separate function to iterate over word and at each numerical value increment the String array index by that value and increment a word_counter variable by 1 to get the number of words in your file.
The skipped indices contain your words (maybe write them to another array).
read () function has a return type size_t and returns the number of bytes read from file, where a return value of 0 signifies that end of file has been reached.
int not_end = 1;
while (not_end)
{
not_end = dat.read((char*)(&temporary), sizeof(temporary));
char *arrray = new char[temporary];
dat.read(arrray, temporary);
string word = string(arrray, temporary);
// Note that word will get overwritten each time the loop is run
// Store word in an array of Strings and keep incrementing index
}

How can I read from the same input file multiple times from different points within the file using sentinel values (-1) in c++?

I have a task where I have to read different sections of an input file(.txt) of integers in c++. The file contains an unknown number of positive integers, each separated by white-space with several sentinel values of -1 placed randomly in the list to "break-up" the list into sections and another -1 at the end of the file.
Here is a sample of my input file(.txt):
3 54 35 4 9 16 -1 14 57 32 4 6 8 41 2 -1 5 6 54 21 3 -1
Here is what I've attempted so far:
int data[20],
index = 0;
ifstream fin;
fin.open("data_file.txt");
while (index < 20 && data[index] != -1 && fin >> data[index])
{
cout << data[index] << endl;
index++;
}
I can't get this to read past the first SV even if I repeat this while loop. It always just starts at the beginning of the file.
How do I read again STARTING AFTER the first SV to the second SV? The only methods I know involve reading a file from beginning to end. How do I read seperate sections?
Thanks in advance for any help,
Cheers
It sounds like you just want to group information from the file. I will not provide code since you didn't, but I may help you with the logic:
Create a file object, 2d vector, and a string
Read from the file object to the string
if the value is equal to "-1", then add a new row. Else, add a new column
The result will be a 2d vector with the rows being each group, and the columns being each positive number in that group.

Reading a file of number into an array while skipping first two values every 1026 entries

I am trying to read in a text file of numbers in which there are 2 values in the beginning that I do not care about, followed by 1024 values that I do care about. The file has approximately 100000 entries that I need to do a calculation on every 1024 of them. The format is something like
1
1025
3000
3572
3579
4023
3593
2930
.
.
.
1
1025
.
.
.
So basically the 1 and the 1025 are header values describing the data set which I need to ignore, then I need to read every value after those header values into an array so I can then run calculations on the values in the array. I was thinking of using while(!file.eof()) but I can not think of how to have the code skip those two numbers while it reads through the 100000 entries. I am pretty new to c++, I usually use GUI's to do my data analysis, but I am on a project that is requiring me to us C++, so I'm really out of my comfort zone here. I appreciate any help I can get.
There are a lot of ways you can do it. The most straight forward example I could think of was:
#include <iostream>
#include <string>
int main()
{
int i = 0;
std::string s;
while( std::cin >> s )
{
if( i++ < 2 ) continue;
std::cout << s;
if( i == 1024 ) i = 0;
}
}

Reading from a file with multiple columns of integers and putting them into arrays

I am creating a command-line minesweeper game which has a save and continue capability. My code generates a file called "save.txt" which stores the position of the mines and the cells that the player has opened. It is separated into two columns delimited by a space where the left column represents the row of the cell and the right column represents the column of the cell in the matrix generated by my code. The following is the contents of save.txt after a sample run:
3 7
3 9
5 7
6 7
8 4
Mine end
2 9
1 10
3 5
1 1
Cell open end
You may have noticed Mine end and Cell open end. These two basically separate the numbers into two groups where the first one is for the position of the mines and the latter is for the position of the cells opened by the player. I have created a code which generates an array for each column provided that the text file contains integers:
int arrayRow[9];
int arrayCol[9];
ifstream infile("save.txt");
int a, b;
while(infile >> a >> b){
for(int i = 0; i < 9; i++){
arrayRow[i] = a;
arrayCol[i] = b;
}
}
As you can see, this won't quite work with my text file since it contains non-integer text. Basically, I want to create four arrays: mineRow, mineCol, openedRow, and openedCol as per described by the first paragraph.
Aside from parsing the string yourself and doing string operations, you can probably redefine the file format to have a header. Then you can parse the once and keep everything in numbers. Namely:
Let the Header be the first two rows
Row 1 = mineRowLen mineColLen
Row 2 = openedRowLen openedColLen
Row 3...N = data
save.txt:
40 30
20 10
// rest of the entries
Then you just read 40 for the mineRow, 30 for mineCol, 20 for openedRow, 10 for openedCol since you know their lengths. This will be potentially harder to debug, but would allow you to hide the save state better to disallow easy modification of it.
You can read the file line by line.
If the line matches "Mine end" or "Cell open end", continue;
Else, split the line by space (" "), and fill the array.