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

时间:2015-08-13 10:43:27

标签: c++ csv

我有一个以下类型的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

注意:没有";"在每一行的末尾。 我想在&#34 ;;"之后存储第二和第三个字符串。在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文件,因此我不知道如何在&#34 ;;"之后评估每一行和每个字符串。

1 个答案:

答案 0 :(得分:0)

getline() 应该是您进行此类解析的朋友:

  • 你可以使用带有分隔符的getline(除了行的最后一个字符串,因为你没有终止&#39 ;;')
  • 或者您只需阅读该行,然后使用 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;           
}

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