[英]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): 我有以下类型的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
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: 在
string img1
和string 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)
}
In the first iteration the strings stored in img1
and img2
shall be 在第一次迭代中,存储在
img1
和img2
的字符串应为
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 ";". 由于我从未使用过csv文件,因此我不知道如何计算“;”之后的每一行和每个字符串。
getline()
shall be your friend for such parsing: getline()
将成为您进行此类解析的朋友:
find()
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. 在这里,更容易处理错误,计数行等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.