在 c++ 中如何将字符串数组转换为浮点数数组?
基本上,我对 C++ 几乎一无所知,只用 Visual Basic 进行过简单的编程。
我希望将 csv 文件中的一堆数字存储为 float
数组。这是一些代码:
string stropenprice[702];
float openprice[702];
int x=0;
ifstream myfile ("open.csv");
if (myfile.is_open())
{
while ( myfile.good() )
{
x=x+1;
getline (myfile,stropenprice[x]);
openprice[x] = atof(stropenprice[x]);
...
}
...
}
无论如何,它说:
错误 C2664:“atof”:无法将参数 1 从“std::string”转换为“const char *”
Basically, I know virtually nothing about C++ and have only programmed briefly in Visual Basic.
I want a bunch of numbers from a csv file to be stored as a float
array. Here is some code:
string stropenprice[702];
float openprice[702];
int x=0;
ifstream myfile ("open.csv");
if (myfile.is_open())
{
while ( myfile.good() )
{
x=x+1;
getline (myfile,stropenprice[x]);
openprice[x] = atof(stropenprice[x]);
...
}
...
}
Anyways it says:
error C2664: 'atof' : cannot convert parameter 1 from 'std::string' to 'const char *'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,你必须说
atof(stropenprice[x].c_str())
,因为atof()
只对 C 风格的字符串进行操作,而不是std::string
对象,但这还不够。您仍然需要将该行标记为以逗号分隔的片段。find()
和substr()
可能是一个好的开始(例如 参见此处),尽管也许更通用的标记化函数会更优雅。这是我很久以前从某个地方偷来的标记器函数,我不记得了,所以对抄袭表示歉意:
用法:
std::vector; v = tokenize(line, ",");
现在对每个字符串使用std::atof()
(或std::strtod()
)向量。这里有一个建议,只是为了让您了解通常如何用 C++ 编写此类代码:
Well, you'd have to say
atof(stropenprice[x].c_str())
, becauseatof()
only operates on C-style strings, notstd::string
objects, but that's not enough. You still have to tokenize the line into comma-separated pieces.find()
andsubstr()
may be a good start (e.g. see here), though perhaps a more general tokenization function would be more elegant.Here's a tokenizer function that I stole from somewhere so long ago I can't remember, so apologies for the plagiarism:
Usage:
std::vector<std::string> v = tokenize(line, ",");
Now usestd::atof()
(orstd::strtod()
) on each string in the vector.Here's a suggestion, just to give you some idea how one typically writes such code in C++: