c++读取csv文件;每行取两个字符串

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

本文关键字:字符串 两个 csv 读取 文件 c++      更新时间:2023-10-16

我有一个以下类型的csv文件(不止三行,这只是为了让您了解大意):

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

注意:每行末尾没有";"。我想在string img1string img2中存储";"之后的第二个和第三个字符串,并遍历csv文件的每一行,如下所示:

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)
}

在第一次迭代中,img1img2中存储的字符串为

img1 = "Output_0000000000005791_RectImgLeft.bmp"
img2 = "Output_0000000000005791_RectImgRight.bmp"
第二次迭代

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

等等…

由于我从未使用过csv文件,我不知道如何评估";"之后的每一行和每个字符串。

getline() 将是您进行这种解析的朋友:

  • 您可以使用带分隔符的getline(除了该行的最后一个字符串,因为您没有终止';')
  • 或者您可以简单地读取该行,然后使用 find()
  • 遍历字符串

,当然还有更多的方法。

例子:

我只选择了这两个,以便您具有读取行和解析字符串中的字符的基础知识。

第一种方法的说明:

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)
}

这种方法的不便之处:由于您不读取整行,因此无法忽略错误输入;在出现第一个错误时,必须停止传递文件。

第二种方法如下:

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;           
}

在这里,更容易处理错误、计算行数等。