sstream读取文件

sstream读取文件对于如下图所示的数据文件:274表示有274个点对,以下每一行代表一个点对,每一行的四个数从左到右依次是一个第一个点的x坐标、y坐标、第二个点的x坐标、y坐标,现在要把点对数和每个点对读取并存储,具体代码如下:#include<iostream>#include<sstream>#include<fstream>#include<string&…

大家好,又见面了,我是你们的朋友全栈君。

对于如下图所示的数据文件:
在这里插入图片描述

274表示有274个点对,以下每一行代表一个点对,每一行的四个数从左到右依次是一个第一个点的x坐标、y坐标、第二个点的x坐标、y坐标,现在要把点对数和每个点对读取并存储,具体代码如下:

#include<iostream>
#include<sstream>
#include<fstream>
#include<string>
#include<vector>
#include<assert.h>
using namespace std;


struct Correspondence2D2D
{
    double p1[2];
    double p2[2];
};
typedef vector<Correspondence2D2D> Correspondences2D2D;

int main(){
	Correspondences2D2D corr_all;
	int n=0;
	ifstream in("correspondences.txt");
	assert(in.is_open());
	string line, word;
    int n_line = 0;
	while(getline(in, line)){
    	stringstream stream(line); //等价于stringstream stream; stream<<line; 向流中传值
        if(n_line==0){
            int n_corrs = 0;
            stream>> n_corrs; //将流中的值读取到n_corrs中
            corr_all.resize(n_corrs);
			cout<<"Total line is "<<n_corrs<<endl;
            n_line ++;
            continue;
        }
        if(n_line>0){

            stream>>corr_all[n_line-1].p1[0]>>corr_all[n_line-1].p1[1]
                  >>corr_all[n_line-1].p2[0]>>corr_all[n_line-1].p2[1];
            cout<<n_line<<" line is "<<corr_all[n_line-1].p1[0]<<" "<<corr_all[n_line-1].p1[1]<<" "
                  <<corr_all[n_line-1].p2[0]<<" "<<corr_all[n_line-1].p2[1]<<endl;
        }
        n_line++;
    }
	return 0;
}

运行结果如下:
在这里插入图片描述

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/136158.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号