Counterfe1t
Counterfe1t

Reputation: 23

How to pull out specific data from char array in cpp?

I'm working on a school project and encountered some difficulties. My program reads a .txt file and assigns it's lines to char array one at a time.

getline(file, line);

char *data = new char[line.length() + 1];

strcpy(data, line.c_str());

// pull out data, convert to int, 
// compare to another variable,
// if true print out the entire line

delete [] data;

So now I've got a char array, eg.:

"-rw-r--r--  1 jendrek Administ   560 Dec 18  2010 CommonTypes.xsd"
/*note that there are multiple space's in the file*/

and what I need to do is I need to pull out the size of the file (eg. 560) from that particular array, convert it to integer and compare it to another variable.

This is where I'm stuck. Tried some of my ideas but they failed and now I'm all out. I will be grateful for every piece of advice!

Upvotes: 2

Views: 1705

Answers (1)

Ziezi
Ziezi

Reputation: 6477

Since you are using C++, you could perform the above action using std::string and std::vector, that will take care of the memory management for you and have a lot of useful member functions, and write something like:

std::ifstream file(file_name);
// ... desired_length, etc

std::string line;
std::vector<string> text;     

// read the text line by line
while (getline (file, line)) {

    // store line in the vector
    text.push_back(line);
}

// scan the vector line by line
for (size_t i = 0; i < text.size(); ++i) {

    // get length of i-th line
    int line_length = text[i].size();

    // compare length
    if (line_length == desired_length) {

        // print line
        std::cout << text[i] <<'\n';
    }
}

If you want to extract data from a line and compare it, you could use std::stringstream, like so:

// initialize a string stream with a line
std::stringstream ss(line);

int variable = 0;

// extract int value from the line 
ss >> variable;    

Depending on the format of each line you may want to define some dummy variables to extract "useless" data.

Upvotes: 1

Related Questions