首页
学习
活动
专区
圈层
工具
发布

换算值
EN

Stack Overflow用户
提问于 2013-11-17 00:59:24
回答 2查看 47关注 0票数 0

我想尝试的是将字符串中的每个值转换为double。让我通过一个例子来解释:

代码语言:javascript
复制
foo.txt
1.5 3 0.2 
6 12.4 16.2

我有一份这样一行的文件。我通过getline()函数一个接一个地得到这些行,并假设我将每行放在一个myLine变量中。现在,我希望将1.5、3和0.2作为一个双,并将其存储到double a变量中。有人知道我怎么能这样做吗?如果有更好的方法,wayI不需要使用getline()获得行。

编辑

代码语言:javascript
复制
int main(){
    ifstream myfile("test.txt");
    string line;

    double d;
    if(myfile.is_open()){

        if(myfile.good()){
            while(getline(myfile,line)){
                   // example line : "0.1 0.5 0.9 0.23 0.12 145 23 12 40 160"
                for(int i=0;i<line.size();i++){ // I want to  store each value in the line into d for a time and print it out.
                    std::stringstream s(line); 
                    s>>d;
                    cout<<d<<endl;
                }
            }
        }


    }
    else{
        cout<<"check the corresponding file"<<endl;
    }

return 0;
}
EN

回答 2

Stack Overflow用户

发布于 2013-11-17 01:02:44

代码语言:javascript
复制
#include <iostream>

using namespace std;

double a, b, c;
cin >> a >> b >> c;

除非你没有固定的单行双倍数,否则谷歌stringstreams就会做你想做的事。

代码语言:javascript
复制
#include <sstream>
#include <string>
#include <vector>

std::stringstream ss (line);

vector<double> result;
double a;
//read all the doubles in the line
while (ss >> a) {
    result.push_back(a);
}

//Now result contains the doubles in the line
//I'm sure there's a way to do that in less lines with insert iterators
票数 0
EN

Stack Overflow用户

发布于 2013-11-17 01:04:26

使用std::stringstream

代码语言:javascript
复制
std::string line = ......;

std::stringstream s(line);
double a,b,c;
s >> a >> b >> c;
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20025914

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档