1

I'm working with a dataset of attributes in a text file which looked something like this:

e,x,y,w,t,a,f,c,b,k,e,c,s,s,w,w,p,w,o,p,n,s,g
e,f,y,y,t,l,f,c,b,w,e,r,s,y,w,w,p,w,o,p,n,y,p
e,b,s,w,t,a,f,c,b,w,e,c,s,s,w,w,p,w,o,p,n,s,g
e,b,s,w,t,a,f,c,b,w,e,c,s,s,w,w,p,w,o,p,k,s,m
e,x,y,n,t,l,f,c,b,w,e,r,s,y,w,w,p,w,o,p,k,y,g
e,b,s,w,t,a,f,c,b,k,e,c,s,s,w,w,p,w,o,p,k,s,g
e,x,f,g,f,n,f,c,n,g,e,e,s,s,w,w,p,w,o,p,n,y,u
e,b,s,y,t,l,f,c,b,k,e,c,s,s,w,w,p,w,o,p,n,s,g

Now, I'm trying to figure out how I can easily read characters from a given column (say, the 5th letter on each line, for example). I can't figure out how to do it though. Does anyone know what I might be able to do?

nym_kalahi
  • 91
  • 1
  • 2
  • 9

2 Answers2

0

Considering the set of data you're dealing with is only one character and NOT of an arbitrary size, you can deduce that each character is followed by a comma, so

1 character = 2 file spaces NOT counting the desired character

If you wanted to read the 5th line, it would be the (4*2 + 1) spot in the file. You could read the line into a string and find it in the string, or just take a single char from the file each time until you've reached the desired number.

cout << "What column would you like to read from? ";
cin >> num;
int Length = (num - 1) * 2 + 1;
char ColumnLetter;
for(int i = 0; i < Length; i++)
{
  inFile >> ColumnLetter;
}
Syntactic Fructose
  • 18,936
  • 23
  • 91
  • 177
0

If there is no whitespaces in your data, every symbol is separated by comma, and ends of the string is one symbol "\n", you can do something like that:

#include <iostream>
#include <fstream>

using std::ifstream;

ifstream file;
const int LINE_WIDTH; //number of your chars in line (without commas)

char GetFromFile(int row, int position) //row and position indexes start from 0!
{
  file.seekg(row * (LINE_WIDTH * 2) + position * 2);
  return file.get();
}

int main()
{
    file.open("data.txt", ios::binary);

    char c = GetFromFile(10, 3);

    file.close();
    return 0;
}
Arsenii Fomin
  • 3,120
  • 3
  • 22
  • 42