简体   繁体   中英

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

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

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM