Fanarosss
Fanarosss

Reputation: 306

How to read data from a specific column in a text file

I'm having a text file with some columns

 name,age,address,gender

I know I can access a line with getline();, but when I get the string with the data that getline(); returned I want to read some specific column. How do I do that ?

I saw a solution to this problem but it was in java which I don't know yet, so I decided to post this for a c++ answer

Upvotes: 1

Views: 3149

Answers (3)

Paul Stelian
Paul Stelian

Reputation: 1379

You may also parse the C string (if you use STL strings do copy the C string to a char array!) using strtok. It will work pretty well, although the need for a separate copy is due to the fact that strtok does modify the string as well as some static memory (or, perhaps, thread-local storage; I wouldn't rely on it)

Upvotes: 0

Gabriel
Gabriel

Reputation: 3594

The approach is the same: read the file line by line and tokenize, while taking the second elem of the array if I want to see the second column. It can be improved because it does lots of copies but the idea is here.

#include <sstream>
#include <string>
#include <boost/algorithm/string.hpp>   

std::string line;
vector<string> strs;
std::ifstream infile("thefile.txt");
while (std::getline(infile, line))
{
    strs.clear();
    boost::split(strs,line,boost::is_any_of("\t"));
    cout<<"age ="<<strs[1]<<endl;
}

Upvotes: 1

user3437460
user3437460

Reputation: 17454

Be it you are asking in Java or C++, the approach will be similar.

After you have read the entire line. Split the line by its delimiter.

In Java, it is just

line.split(",");

In C++, you could use str.find(",") to get the position of the comma. Then substring the delimited tokens out.

Set a count variable to count number of tokens you have delimited so far to get to your desired column.

Upvotes: 1

Related Questions