[英]how to read integers (two per line) into separate arrays from a text file in c++
[英]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()
将成为您进行此类解析的朋友:
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;
}
在这里,更容易处理错误,计数行等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.