¿Cómo leo un carácter específico en una línea de un archivo?

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?

preguntado el 04 de diciembre de 12 a las 04:12

Nope, just read line by line, then pick out the character you want. -

2 Respuestas

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 NO 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;
}

Respondido el 04 de diciembre de 12 a las 04:12

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;
}

Respondido el 04 de diciembre de 12 a las 04:12

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.