C++ 转换值
我想尝试的是将字符串中的每个值转换为double。让我通过以下示例来解释:C++ 转换值,c++,file-io,C++,File Io,我想尝试的是将字符串中的每个值转换为double。让我通过以下示例来解释: foo.txt 1.5 3 0.2 6 12.4 16.2 我有一个这样一行的文件。我通过getline()函数一行一行地获取这些行,并假设我将每一行放入一个myLine变量中。现在我想将1.53和0.2分别作为一个double存储到double a变量中。有人知道我怎么做吗? 顺便说一下,如果有更好的方法,我不必使用getline()获取行 编辑 int main(){ ifstream myfile("t
foo.txt
1.5 3 0.2
6 12.4 16.2
我有一个这样一行的文件。我通过getline()函数一行一行地获取这些行,并假设我将每一行放入一个myLine变量中。现在我想将1.53和0.2分别作为一个double存储到double a
变量中。有人知道我怎么做吗?
顺便说一下,如果有更好的方法,我不必使用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;
}
intmain(){
ifstream myfile(“test.txt”);
弦线;
双d;
如果(myfile.is_open()){
if(myfile.good()){
while(getline(myfile,line)){
//示例行:“0.1 0.5 0.9 0.23 0.12 145 23 12 40 160”
对于(int i=0;i>d;
不能使用std::stringstream
:
std::string line = ......;
std::stringstream s(line);
double a,b,c;
s >> a >> b >> c;
ı在前两行中,我每行有一个数字,每行将有10个数字。你能更具体一点吗?编辑后的答案以字符串流为例,你能看一下我的编辑吗?我是这样做的,但不起作用。如果你只想得到每行的第一个数字,则不需要最后的嵌套for循环。剪掉循环(但保持字符串流等)。如果你想要每一行的所有数字,算法仍然不同,但没有确认这就是你的目标,我不能确定。你想处理每一行,并在这样做时,处理该行上的所有数字吗?@WhozCraig谢谢你的回复。我想一行一行地读取所有值,并将int存储到vector中。进行一些操作在这一行挂起,然后移到文件的第二行,直到eof。你知道怎么做吗?好的。这段代码非常简单。除非有人先挂起,否则我会发布一个响应。@WhozCraig非常感谢
#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
std::string line = ......;
std::stringstream s(line);
double a,b,c;
s >> a >> b >> c;