Pregunta

Actualmente estoy tratando de tomar una cadena ( "0.1") y convertirlo en un doble usando C ++ en Xcode en 10.6 con gcc4.2.

Estoy usando una función Pellizqué de otra pregunta , pero cuando intento para utilizar la función, mi entrada de acuerdo con gdb es (cadena) "0.1", pero mi salida es (doble) 2.1220023981051542e-314.

Aquí está mi fragmento copiado directamente el 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;
};

Estoy usando C ++ en lugar de Obj-C, ya que probablemente tendrán que ser compilado en una máquina * nix o Windows con el tiempo.

estoy, naturalmente, un programador de PHP, pero tienen algunos cálculos numéricos que necesito para acelerar, por lo que estoy haciendo en un lenguaje compilado. Ha sido un largo tiempo desde la Universidad se trata de un lenguaje de bajo nivel = P. Por lo tanto, si alguien tiene una idea, que sería muy apreciada ...

a 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;
}
¿Fue útil?

Solución

Esto puede ser causado por el modo de STL de depuración. Quitar las macros _GLIBCXX_DEBUG en el establecimiento de la acumulación preprocesador macros de tu objetivo.

C ++ versiones de depuración rompió en Snow Leopard X-Code

Otros consejos

¿Por qué no usar atof () en su lugar? enlace

No puedo ver nada mal con su fragmento de código. ¿Puede mostrar el código que está utilizando a salida el resultado

Como sugirió Myles, atof () podría ser más simple. Puede convertir un objeto de cadena en una cadena c llamando a la función miembro c_str ():

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

Aquí hay más información: 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;
}

El código anterior me da el siguiente resultado:
    -2.36907e-39
    0.1

¿Es usted por casualidad comprobando el valor de doubleValue antes de regresar?


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;
}

Salida:
    tEmPLat = 0.1
    latDouble = 0.1
    Templat = 0,4
    latDouble = 0,4

¿Se puede ejecutar el código con estas modificaciones (no se está usando el parámetro int en el ctor, por lo que sólo es eliminado). También me encontré con el código utilizando valgrind sin errores (sólo pérdidas de memoria).

Parece que no has encontrado la respuesta a su problema implemetion. Otros han sugerido el uso de atof (). Si desea resolver el problema en su IMPLEMENTACIÓN, entonces mirar el código de abajo. En lugar de tener vector de explotar método, puesto vectores para evitar código redundante. He cambiado el código en strToDouble también.

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 bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top