简体   繁体   中英

C++ read csv file; get two strings per line

I have a csv file of the following type (more than only three line, this is just that you get the idea):

0000000000005791;Output_0000000000005791_RectImgLeft.bmp;Output_0000000000005791_RectImgRight.bmp
0000000000072517;Output_0000000000072517_RectImgLeft.bmp;Output_0000000000072517_RectImgRight.bmp
0000000000137939;Output_0000000000137939_RectImgLeft.bmp;Output_0000000000137939_RectImgRight.bmp

Note: There is no ";" at the end of each line. I'd like to store the second and third string after the ";" in a string img1 and string img2 and iterate over each row of the csv file, so something like this:

ifstream read_file ( "file.csv" )

while ( read_file.good() ){
      string img1 = get_string_after_first_semicolon;
      string img2 = get_string_after_second_semicolon;
      do_stuff(img1, img1)
}

In the first iteration the strings stored in img1 and img2 shall be

img1 = "Output_0000000000005791_RectImgLeft.bmp"
img2 = "Output_0000000000005791_RectImgRight.bmp"

in the second iteration

img1 = "Output_0000000000072517_RectImgLeft.bmp"
img2 = "Output_0000000000072517_RectImgRight.bmp"

and so forth...

As I've never worked with csv files I don't know how to evaluate each line and each string after a ";".

getline() shall be your friend for such parsing:

  • you could either use getline with delimiter (except for the last string of the line as you have no terminating ';')
  • or you could simply read the line with it, and iterate through the string with find()

and there are certainly many more ways.

Examples:

I just picked these two, so that you have the basics to read lines and parse characaters in strings.

Illustration of the first approach:

ifstream read_file ( "file.csv" )
string s1,s2,s3; 
while ( getline(read_file,s1,';') &&  getline(read_file,s2,';') &&  getline(read_file,s3) ){
      string img1 = s2;
      string img2 = s3;
      do_stuff(img1, img1)
}

Inconvenience of this approach: as you don't read full lines, you can't ignore wrong input; at the first error you have to stop pasring the file.

The second approach would look like:

string line; 
while ( getline(read_file, line) ){
      int pos1 = line.find(';');  // search from beginning
      if (pos1 != std::string::npos) { // if first found
         int pos2 = line.find (';',pos1+1); 
         if (pos2 != std::string::npos) {
            string img1 = line.substr(pos1+1, pos2-pos1-1); 
            string img2 = line.substr(pos2+1);
            do_stuff(img1, img2);
         }
         else cout << "wrong line, missing 3rd item"<<endl;
      }
      else cout << "wrong line, missing 2nd and 3rd item"<<endl;           
}

Here, it's easier to process errors, count lines, etc.

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