C + + reads the text file with tab as the delimiter, and the middle field has an empty case method?

Source: Internet
Author: User

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?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.