user2158031
user2158031

Reputation: 81

Reading in a specific column of data from a text file in C

My text file looks like this:

987 10.50   N   50
383 9.500   N   20
224 12.00   N   40

I want to read only the second column of data. How would I got about doing this?

Upvotes: 3

Views: 16173

Answers (4)

Galik
Galik

Reputation: 48615

In C++ you could consider using std::istringstream, which requires the include: #include <sstream>. Something like:

std::ifstream ifs("mydatafile.txt");

std::string line;

while(std::getline(ifs, line)) // read one line from ifs
{
    std::istringstream iss(line); // access line as a stream

    // we only need the first two columns
    int column1;
    float column2;

    iss >> column1 >> column2; // no need to read further

    // do what you will with column2
}

What std::istringstream does is allow you to treat a std::string like an input stream just like a regular file.

The you can use iss >> column1 >> column2 which reads the column data into the vaiables.

Upvotes: 1

acarlow
acarlow

Reputation: 924

C89/C90 has the function strtok that could be used to read the file line by line, separate the columns with the "space" delimiter and then you could access the nth token (representing the nth column in that row in the file).

strtok is declared in

http://cplusplus.com/reference/cstring/

Some implementations also have a thread-safe re-entrant version called strtok_r.

Upvotes: 2

You'll need to read all the data, and discard the unneeded fields (i.e. "columns"). Format strings containing %*d are doing that.

In C, it could be something like (assuming f is a FILE* handle)

 while (!feof(f)) {
    int n=0; double x=0.0; char c[4]; int p=0;
    if (fscanf(f, " %*d %f %*[A-Z] %*d",  &x) < 1)
      break;
    do_something(x);
 }

PS. Thanks to Jerry Coffin for his comment

Upvotes: 5

Jerry Coffin
Jerry Coffin

Reputation: 490148

You can't just read the second column without reading anything else.

What you can do is read all the data, and ignore everything but the second column. For example, read a line of data (with std::getline) then from it extract an int and a double, but ignore both the int and the rest of the line.

Upvotes: 5

Related Questions