0

I want to read data from a file with a quite strange structure. The file looks like this below:

some lines with text....

10 1000  10
 1    1   1
 1  100 100 
    .
    .
    .

some lines with text... 

again data like above..

some lines with text... etc

So I have two questions:

  1. How can I read only the specific lines with the data?

  2. How can I read these right aligned data?

Here is one of my trials:

string line;
ifstream myfile ("aa.txt");

double a,b,c;

while (! myfile.eof() )
{
  for (int lineno = 0; getline (myfile,line); lineno++)
  if (lineno>2 && lineno<5){

myfile>>a>>b>>c;

  cout<<lineno<<"      " << line << endl;}


}
myfile.close();
techraf
  • 64,883
  • 27
  • 193
  • 198

2 Answers2

0
  1. how can I read only the specific lines with the data?

    well, read all the lines, and then write a function to detect whether the current line is a "data" one or not.

    What are the characteristics of your data line? It consists only of digits and spaces? Could there be tabs? What about the columns, are they fixed width? Your predicate function can check there are spaces in the required columns if so.

  2. how can I read these right aligned data?

    You want to extract the integer values? Well, you can create a std::istringstream for your line (once you've checked it is data), and then use the >> stream extraction operator to read values into variables of the appropriate type.

    Read up on how it handles whitespace (and/or experiment) - it might just do what you need with no effort.

Useless
  • 64,155
  • 6
  • 88
  • 132
0

this is just a simple example: you declare 3 variables as you did a, b , c as integer and a string line you open a file and input line convert line to integer if ok assign it to a if not don't do anything to b and c until next read until a valid conversion for a is ok then input b and c and like this:

#include <iostream>
#include <string>
#include <fstream>


int main()
{
    std::ifstream in("data.txt");
    int a = 0, b = 0, c = 0;
    std::string sLine;

    if(in.is_open())
    {
        while(in >> sLine)
        {
            if( a = atoi(sLine.c_str()))
                std::cout << "a: " << a << std::endl;

            if(a)
            {
                in >> sLine;
                if( b = atoi(sLine.c_str()))
                    std::cout << "b: " << b << std::endl;
            }

            if(b)
            {
                in >> sLine;
                if( c = atoi(sLine.c_str()))
                    std::cout << "c: " << c << std::endl;
            }
        }

    }

    in.close();

    std::cout << std::endl;
    return 0;
}
Raindrop7
  • 3,889
  • 3
  • 16
  • 27