我想尝试的是将字符串中的每个值转换为double。让我通过一个例子来解释:
foo.txt
1.5 3 0.2
6 12.4 16.2我有一份这样一行的文件。我通过getline()函数一个接一个地得到这些行,并假设我将每行放在一个myLine变量中。现在,我希望将1.5、3和0.2作为一个双,并将其存储到double a变量中。有人知道我怎么能这样做吗?如果有更好的方法,wayI不需要使用getline()获得行。
编辑
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;
}发布于 2013-11-17 01:02:44
#include <iostream>
using namespace std;
double a, b, c;
cin >> a >> b >> c;除非你没有固定的单行双倍数,否则谷歌stringstreams就会做你想做的事。
#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发布于 2013-11-17 01:04:26
使用std::stringstream
std::string line = ......;
std::stringstream s(line);
double a,b,c;
s >> a >> b >> c;https://stackoverflow.com/questions/20025914
复制相似问题