Question

I've spent a lot of time looking online to find a answer for this, but nothing was helping, so I figured I'd post my specific scenario. I have a .txt file (see below), and I am trying to write a routine that just finds a certain chunk of a certain line (e.g. I want to get the 5 digit number from the second column of the first line). The file opens fine and I'm able to read in the entire thing, but I just don't know how to get certain chunks from a line specifically. Any suggestions? (NOTE: These names and numbers are fictional...)

//main cpp file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
    ifstream fin;
    fin.open("customers.txt");



    return 0;
}

//customers.txt
100007     13153     09067.50     George F. Thompson
579489     21895     00565.48     Keith Y. Graham
711366     93468     04602.64     Isabel F. Anderson
Was it helpful?

Solution 2

Some simple hints in your code to help you, you will need to complete the code. But the missing pieces are easy to find at stackoverflow.

//main cpp file
#include <iostream>
#include <fstream>
#include <string>
#include <vector>

using namespace std;

splitLine(const char* str, vector<string> results){
    // splits str and stores each value in results vector
}

int main()
{
    ifstream fin;
    fin.open("customers.txt");
    char buffer[128];
    if(fin.good()){
        while(!fin.eof()){
            fin.getline(buffer, 256);
            cout << buffer << endl;

            vector<string> results;         
            splitLine(buffer, results);
            // now results MUST contain 4 strings, for each 
            // column in a line
        }

    }
    return 0;
}

OTHER TIPS

Text parsing is not such a trivial thing to implement.

If your format won't change you could try to parse it by yourself, use random access file access and use regular expressions to extract the part of the stream that you need, or read a certain quantity of chars.

If you go the regex way, you'll need C++11 or a third party library, like Boost or POCO.

If you can format the text file then you might also want to choose a standard to structure your data, like XML, and use the facilities of that format to extract the information you want. POCO might help you there.

If the columns are separated by whitespace then the second column of the first row is simpy the second token extracted from the stream.

std::ifstream input{"customers.txt"}; // Open file input stream.
std::istream_iterator<int> it{input}; // Create iterator to first token.
int number = *std::next(it);          // Advance to next token and dereference.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top