栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++ 文件读取(按行读取,每行以空格隔开,并转成double)

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++ 文件读取(按行读取,每行以空格隔开,并转成double)

#include
#include 
#include 
#include  //字符串转换
#include 


using namespace std;




int main()
{
	ifstream fin("test.txt");
	string line;
	vector location_1, location_2, location_3;

	if (fin)
	{
		while (getline(fin, line)) //按行读取到line_info中 
    	{
			if (line.size() == 0)
			{
				break;   //循环体内手动的进行空行的判断
			}
			//cout << "line:" << line << endl;
			istringstream sin(line); //create string input object
			vector Waypoints;
			string info;

			while (getline(sin, info, ' '))
			{
				//cout << "info:" << info << endl;
				Waypoints.push_back(info);
			}

			string x1_str = Waypoints[0];
			string x2_str = Waypoints[1];
			string x3_str = Waypoints[2];
			// cout<< "x_str" << x_str << endl;
			// cout<< "y_str" << y_str << endl;

			double x1, x2, x3;
			stringstream sx1, sx2, sx3; //transform string to double

			sx1 << x1_str;
			sx2<< x2_str;
			sx3 << x3_str;
			sx1 >> x1;
			sx2 >> x2;
			sx3>> x3;
			location_1.push_back(x1);
			location_2.push_back(x2);
			location_3.push_back(x3);
		}
	}
	else
	{
		cout << "no such file" << endl;;
	}
	fin.close();
	for (int j = 0; j < location_1.size(); j++)
	{
		cout << "location_1[" << j << "]: " << location_1[j] << " ";
		cout << "location_2[" << j << "]: " << location_2[j] <<" " ;
		cout << "location_3[" << j << "]: " << location_3[j] <<" " ;
		cout << endl;
	}
	return 0;
}

 处理istream流额时候,getline()的返回值是这样的:
只要可以读到文件内容(包括空行),返回值就一直是True. 如果读取失败,那么会抛出相对应的异常。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/883135.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号