Parsing a string in c++ using header file and cpp file
I am able to r开发者_如何学Pythonead my text file. Now i would like to parse the string line by line. I am using header file and cpp file.. can anyone help me with parsing tutorial. Where can find a good tutorial for parsing?
You can try http://www.cppreference.com/wiki/ and look at examples of using stringstreams.
I don't see what this has to do with header files, but here's how you parse a stream line by line:
void read_line(std::istream& is)
{
// read the lisn from is, for example: reading whitespace-delimited words:
std::string word;
while(is >> word)
process_word(word);
if( !is.eof() ) // some other error?
throw "Dude, you need better error handling!";
}
void read_file(std::istream& is)
{
for(;;)
{
std::string line;
if( !std::getline(is,line) )
break;
std::istringstream iss(line);
read_line(iss);
}
if( !is.eof() ) // some other error?
throw "Dude, you need better error handling!";
}
Try this:
#include <iostream>
#include <vector>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream fs("myFile.txt");
string input;
vector<string> sets;
while( getline(fs, input) )
sets.push_back(input);
}
First you need to know if the lines contain fixed length fields or are the fields variable length. Fixed length fields are usually padded with some character such as spaces or zeros. Variable length fields are usually terminated by a character such as a comma or tab.
Variable Length Fields
Use the std::string::find
or std::string::find_first
to find the ending character; also account for the end of the string as the last field may not contain the terminating character. Use this position to determine the length of the field (ending field position - starting field position). Finally, use std::string::substr
to extract the field's content.
Fixed Length Fields
Use the std::string::substr
method to extract the text. The starting and ending positions can be calculated using the accumulated lengths of the previous fields, if any, and the size of the current field.
Converting Field Text
The contents of the field may not be a string and will need to be converted to an internal data type. For example, a number. Use std::istringstream
to convert the text of the field to an internal data type.
精彩评论