2015-08-13 96 views
1

兩個字符串我有以下類型的csv文件(超過只有三線,這僅僅是你的想法):C++讀取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文件,我不知道如何評估每行和每個字符串後「;」。

+0

只是逐行讀取文件中的行和分析每一行。你知道如何逐行讀取文件嗎?你知道如何在一個角色上分割一個字符串嗎? –

+0

如何逐行讀取文件並照顧正確的字符串拆分?這是exaclty我的問題;) – SemtexB

+0

如何逐行讀取文件?或者如何在分隔符處分割字符串?這些都是與CSV文件無關的基本操作。 –

回答

0

getline()應是你的朋友,這樣的分析:

  • ,你既可以使用帶分隔符函數getline(除行的最後一個字符串作爲你沒有終止「;」)
  • 或你可以簡單地閱讀它的線,並通過字符串find()

迭代,並有certa還有更多的方法。

例子:

我剛撿到的這兩個,讓你有基本閱讀線和串解析characaters。

插圖第一種方法:

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

這裏,很容易處理的錯誤,計算行等