string转成double以及空白行

askprog 2013-09-16 01:42:53
请问把一个string变成double,比如string s="12 13 14.5 16 18"
有什么办法把这string变成12,13,14.5,16,18这5个double数
用c中的strtod?c++中有什么办法?
如果只想只知道这一行有多少个数字又什么办法?

还有就是一个txt文件有很多行,其中有很多空白行,如何知道那一行是空白行?
...全文
151 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
c++这么来写

#include "stdafx.h"
#include "stdio.h"
#include <string>
#include <vector>
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
	string s="12 13 14.5 16 18";
	vector<double> fvec;
	size_t npos=s.find(" ");
	size_t ipos=0;
	 while(npos!=string::npos)
	 {
		 s.substr(ipos,npos);
		 fvec.push_back(atof(s.substr(ipos,npos).c_str())); 
		 ipos=npos;
		 npos=s.find(" ",ipos+1);
	 }
	vector<double>::iterator itor;
	itor=fvec.begin();
	while(itor!=fvec.end())
	{
		cout<<*itor++<<endl;
	}
	return 0;
}
modyaj 2013-09-16
  • 打赏
  • 举报
回复
自己先分割以后 再调用库函数处理
大尾巴猫 2013-09-16
  • 打赏
  • 举报
回复
用stream流,可以像cin一样进行抽取
	istringstream iss(s);
	vector<double> vd;
	double temp;
	iss >> temp;
	while (iss)
	{
		vd.push_back(temp);
		iss >> temp;
	}
数量可由 vd.size()获得 判断text文件空行,用getline(cin,string)读取,判断string == ""就是空行。
max_min_ 2013-09-16
  • 打赏
  • 举报
回复
引用 2 楼 max_min_ 的回复:

double  atof(string);
先分割字符串

1 strtok();
2 atof();
max_min_ 2013-09-16
  • 打赏
  • 举报
回复

double  atof(string);
qq120848369 2013-09-16
  • 打赏
  • 举报
回复
istringstream可以方便一些。
zwb_1988 2013-09-16
  • 打赏
  • 举报
回复
你只要用空格符来区分每个数值,放入数组,然后在转成double就行啦。 至于空白行,你可以做长度判定。或者用上面的方法来得到数组,数组为空,就是空白行。 读文件的时候一行行度.

69,371

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧