Pergunta

Atualmente estou tentando dar uma string ( "0.1") e convertê-lo em um duplo usando C ++ no Xcode em 10,6 com gcc4.2.

Eu estou usando uma função belisquei de outra pergunta , mas quando eu tento usar a função, a minha entrada de acordo com gdb é (string) "0.1", mas a minha saída é (duplo) 2.1220023981051542e-314.

Aqui está o meu trecho copiado direto do código:

double strToDouble(std::string const &numberString)
{
    istringstream inStream(numberString);
    double doubleValue;
    inStream >> doubleValue;
    if(!(inStream && (inStream >> std::ws).eof()))
    {
        return 0.0;  
    }

    return doubleValue;
};

Eu estou usando C ++ em vez de Obj-C, uma vez que provavelmente terá que ser compilado em um * nix ou Windows máquina eventualmente.

Eu sou naturalmente um programador PHP, mas ter algum processamento de números que eu preciso para acelerar, então eu estou fazendo isso em uma linguagem compilada. Tem sido um longo tempo desde Universidade lidar com uma linguagem de nível inferior = P. Então, se alguém tem idéias, seria muito apreciada ...

de Drew J. Sonne.

código completo:

#include <iostream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;

/*
 * @var delimiters the string to define a break by
 * @var str the string to break
 * @var tokens where to store the broken string parts.
 */
void explode(const string& delimiters, const string& str, vector<string>& tokens)
{
    // Skip delimiters at beginning.
    string::size_type lastPos = str.find_first_not_of(delimiters, 0);
    // Find first "non-delimiter".
    string::size_type pos     = str.find_first_of(delimiters, lastPos);

    while (string::npos != pos || 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);
    }
};

/*
 * @var numberString double to be converted as a string.
 */
double strToDouble(std::string const &numberString)
{
    istringstream inStream(numberString);
    double doubleValue;
    inStream >> doubleValue;
    if(!(inStream && (inStream >> std::ws).eof()))
    {
        return 0.0;  
    }

    return doubleValue;
};

class Cluster {
private:
    vector<double> latStore;
    vector<double> lngStore;
public:
    Cluster(int,string,string);
};

/*
 * @var latString a comma seperated list of doubles for the latitudes.
 * @var lngString a comma separated list of doubles for the longitudes.
 */
Cluster::Cluster(int newLocationLength, string latString, string lngString)
{
    // mark our vectors
    vector<string> latStoreString;
    vector<string> lngStoreString;

    // Explode our input strings.
    explode(",", latString, latStoreString);
    explode(",", lngString, lngStoreString);

    for( int i = 0; i < latStoreString.size(); i++)
    {
        // Grab the latitude and store it.
        string tempLat = latStoreString[i];
        double latDouble = strToDouble(tempLat);
        latStore.push_back( strToDouble(tempLat) );

        // Grab the longitude and store it.
        string tempLng = lngStoreString[i];
        lngStore.push_back( strToDouble(tempLng) );
    }
}

int main (int argc, char * const argv[]) {

    Cluster *rect = new Cluster("0.1,0.4","0.1,0.4");

    return 0;
}
Foi útil?

Solução

Isso pode ser causado pelo modo STL Debug. Remova as macros _GLIBCXX_DEBUG na configuração construção Preprocessor Macros do seu alvo.

C ++ Debug constrói quebrou no Snow Leopard X-Code

Outras dicas

Por que não usar atof () em vez disso? ligação

Eu posso ver errado nada com o seu fragmento de código. você pode mostrar o código que você está usando para saída o resultado

Como Myles sugeriu, atof () poderia ser mais simples. Você pode converter um objeto string para uma string c chamando a função de membro c_str ():

double result = atof(inputString.c_str()); // 0.0 if a double couldn't be read

Aqui está mais algumas informações: http://www.cplusplus.com/reference / clibrary / cstdlib / atof /

#include <iostream>
#include <sstream>

double strToDouble(std::string const &numberString)
{
    std::istringstream inStream(numberString);
    double doubleValue;
    std::cout << doubleValue << '\n';
    inStream >> doubleValue;
    if(!(inStream && (inStream >> std::ws).eof()))
    {
        return 0.0;  
    }

    return doubleValue;
};

int main()
{
    std::cout << strToDouble("0.1") << '\n';

    return 0;
}

O código acima dá-me o seguinte resultado:
-2.36907e-39
0,1

Você por acaso verificando o valor da doubleValue antes de retornar?


Cluster::Cluster(string latString, string lngString)
{
    // mark our vectors
    vector<string> latStoreString;
    vector<string> lngStoreString;

    // Explode our input strings.
    explode(",", latString, latStoreString);
    explode(",", lngString, lngStoreString);

    for( int i = 0; i < latStoreString.size(); i++)
    {
        // Grab the latitude and store it.
        string tempLat = latStoreString[i];
        std::cout << "tempLat=" << tempLat << '\n';
        double latDouble = strToDouble(tempLat);
        std::cout << "latDouble=" << latDouble << '\n';
        latStore.push_back( strToDouble(tempLat) );

        // Grab the longitude and store it.
        string tempLng = lngStoreString[i];
        lngStore.push_back( strToDouble(tempLng) );
    }
}

int main (int argc, char * const argv[]) {

    Cluster *rect = new Cluster("0.1,0.4","0.1,0.4");

    return 0;
}

Saída:
Templat = 0,1
latDouble = 0,1
Templat = 0,4
latDouble = 0,4

Você pode executar o código com estas modificações (você não estava usando o parâmetro int no ctor, então eu só removeu). Eu também corri o seu código usando valgrind sem erros (apenas vazamentos de memória).

Parece que você não obter resposta para o seu problema implemetion. Outros sugeriram usar atof (). Se você gostaria de resolver o problema em sua IMPLEMENTAÇÃO, em seguida, fazer olhada no código abaixo. Em vez de ter vector para explodir método, colocar vector para evitar código redundante. Mudei o código no strToDouble também.

void explode(const string& delimiters, const string& str, vector<double>& tokens)
{    
     // Skip delimiters at beginning.   
     string::size_type lastPos = str.find_first_not_of(delimiters, 0);   
     // Find first "non-delimiter".    
     string::size_type pos = str.find_first_of(delimiters, lastPos);
     while (string::npos != pos || string::npos != lastPos)   
     {        
              // Found a token, add it to the vector.       
             string temp = str.substr(lastPos, pos - lastPos);
             tokens.push_back(strToDouble(temp));    
             // 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);    
     }
}

double strToDouble(std::string const &numberString)
{  
   istringstream inStream(numberString);    
   int pos = numberString.find_first_not_of("1234567890.", 0);

   if (string::npos != pos)
   {
       return 0.0;
   }
   else
   {
      double doubleValue;   
      inStream >> doubleValue;        
      return doubleValue;
  }
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top