Data file: TestData.txt
Content:
111 222 444 555
Ideas:
Getline () reads the first row of records in the TestData.txt into a string, searches for the nth delimiter to locate, determines the nth field length, uses substr, intercepts the field, and assigns a value to the target string.
Program:
#include <iostream> #include <fstream>using namespace std;void getstringfromcsv (std::string line, int nidx, std::string &str) {int nspos = 0;//record start position for (int i = 0; i < nIdx-1; ++i) {Nspos = Line.find (' \ t ', nspos);//Open from Nspos Start looking for the next tab++nspos;//the next character from the currently found ' \ t ' key position, begin looking for}int Nepos = line.find (' \ t ', nspos);//Find the end position of the third field if (Nepos! = String::npos )//Find the tab character {str = LINE.SUBSTR (Nspos, nepos-nspos);} Else{str = Line.substr (Nspos, Line.size ()-1-nspos);}} int main (void) {string starget, Line;ifstream in ("./testdata.txt"), if (!in.is_open ()) {cout << "open./ TestData.txt fail! "<< endl;return-1; }getline (in, line); Getstringfromcsv (line, 3, starget); cout << "./testdata.txt the contents of the third field in the first row of records that are tab-delimited are:" << starget << Endl;in.close (); return 0;}
PS: Just modify ' \ t ' to apply files separated by other separators.
C + + reads the text file with tab as the delimiter, and the middle field has an empty case method?