簡體   English   中英

如何在C ++中將字符串數組轉換為浮點數數組?

[英]How do you convert an array of strings to an array of floats in 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 *'

好吧,您不得不說atof(stropenprice[x].c_str()) ,因為atof()僅適用於C樣式的字符串,而不適用於std::string對象,但這還不夠。 您仍然必須將行標記為逗號分隔的部分。 find()substr()可能是一個不錯的開始(例如, 參見此處 ),盡管也許更通用的標記化功能會更優雅。

這是我很久以前從不記得的地方偷來的一個分詞器功能,為for竊道歉:

std::vector<std::string> tokenize(const std::string & str, const std::string & delimiters)
{
  std::vector<std::string> tokens;

  // Skip delimiters at beginning.
  std::string::size_type lastPos = str.find_first_not_of(delimiters, 0);
  // Find first "non-delimiter".
  std::string::size_type pos     = str.find_first_of(delimiters, lastPos);

  while (std::string::npos != pos || std::string::npos != lastPos)
  {
    // Found a token, add it to the vector.
    tokens.push_back(str.substr(lastPos, pos - lastPos));
    // Skip delimiters.  Note the "not_of"
    lastPos = str.find_first_not_of(delimiters, pos);
    // Find next "non-delimiter"
    pos = str.find_first_of(delimiters, lastPos);
  }

  return tokens;
}

用法: std::vector<std::string> v = tokenize(line, ","); 現在在向量中的每個字符串上使用std::atof() (或std::strtod() )。


這是一個建議,只是為了讓您了解一下通常如何用C ++編寫這樣的代碼:

#include <string>
#include <fstream>
#include <vector>
#include <cstdlib>

// ...

std::vector<double> v;

std::ifstream infile("thefile.txt");
std::string line;

while (std::getline(infile, line))
{
  v.push_back(std::strtod(line.c_str(), NULL));  // or std::atof(line.c_str())
}

// we ended up reading v.size() lines

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM