Pages : 1
#1 Le 05/03/2013, à 20:06
- kboo
c++ atof ....
Bonjour,
Je n'arrive pas à faire la conversion d'une string vers un double avec atof dans mon exemple, et je ne comprend pas du tout pourquoi!
#include <sstream>
#include <iostream>
#include <vector>
#include <cstdlib>
using namespace std;
vector<string> split(string str, char separateur) {
vector<string> strings;
istringstream f(str);
string s;
while (getline(f, s, separateur)) {
//cout << s << endl;
strings.push_back(s);
}
return strings;
}
int main(void)
{
cout << split("toto\tzerze\tmlml", '\t')[1] << endl;
double eee = atof(split("111\t222",'\t')[0]);
}
qui me renvoi :
aaa.cpp:22: error: cannot convert ‘std::basic_string<char, std::char_traits<char>, std::allocator<char> >’ to ‘const char*’ for argument ‘1’ to ‘double atof(const char*)’
Mais je ne comprend pas du tout pourquoi
merci beaucoup pour votre aide!!
Hors ligne
#2 Le 05/03/2013, à 20:44
- pingouinux
Re : c++ atof ....
Bonsoir,
Il faut utiliser la méthode c_str :
double eee = atof(split("111\t222",'\t')[0].c_str());
Ajouté :
Voir std::string::c_str, dont voici le début :
public member function
std::string::c_str <string>const char* c_str() const;
Get C string equivalent
Returns a pointer to an array that contains a null-terminated sequence of characters (i.e., a C-string) representing the current value of the string object.This array includes the same sequence of characters that make up the value of the string object plus an additional terminating null-character ('\0') at the end.
Dernière modification par pingouinux (Le 05/03/2013, à 21:10)
Hors ligne
#3 Le 06/03/2013, à 04:40
- grim7reaper
Re : c++ atof ....
Bonjour,
Il faut arrêter de faire du C en C++.
Le moyen de faire ça proprement en C++ c’est :
#include <sstream>
int main()
{
std::cout << split("toto\tzerze\tmlml", '\t')[1] << '\n';
std::istringstream iss(split("111\t222",'\t')[0]);
double eee;
iss >> eee;
}
Cf. ici.
D’ailleurs, même en C on n’utilisera pas atof (qui est déprécié, car aucune gestion d’erreur), mais strtod ou équivalent.
Dernière modification par grim7reaper (Le 06/03/2013, à 04:43)
Hors ligne
Pages : 1