c++读取csv文件;每行取两个字符串
C++ read csv file; get two strings per line
我有一个以下类型的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 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)
}
在第一次迭代中,img1
和img2
中存储的字符串为
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;
}
在这里,更容易处理错误、计算行数等。
相关文章:
- 两个字符串在 c++ 中不相等
- 在C++的两个字符串中连接以逗号分隔的唯一值
- 将字符串拆分为标记,并将标记拆分为两个单独的数组
- 如何从文件中读取两个字符串和数字数组,并将它们存储在对象向量中
- 比较两个字符串后卡在无限循环中
- 我已经建立了递归关系,它找到了两个字符串之间最长的连续公共字符串,我怎么能跳过其中一个字符串中的一个字符
- 使用XOR查找O(n)-解决方案中的两个字符串是否为变位符
- 如何将字符串和整数读取到两个单独的动态数组中的程序编写?
- 如何将两个字符串加在一起,就好像它们是变量一样?
- 我需要帮助在一个类中输入两个字符串并获取其输出
- 这两个C++语句连接字符串有什么区别?
- 两个字符串之间的数学运算
- 使用 SET(C++) 检查两个给定字符串是否是字谜时出现运行时错误
- 有没有办法我可以在 C++ 中使用 if 语句来说明如果一个字符串不是两个名称的 eqal,它会给出一个输出,ATM i
- 如何在 main 函数中输出两个新字符串C++?
- sscanf() 有两个字符串参数
- 我的字符串数组一次打印出前两个字符串
- 两个 c++ 字符串上的异或
- 函数返回两个字符串的第一个常用字符
- 目标是找到两个 c 字符串之间的公共前缀(必须使用特定的函数标头)