vendredi 27 mars 2015

How to convert a String to int? [duplicate]


This question already has an answer here:




ive been working on this because I can't use stoi from the new compilators. My code is meant to receive a String and save in entero (int) the converted string. I need this to start working on my Metaheuristics homework but I cant even read the data properly from a file :(. It doesnt work properly, it only saves in entero the first digit of the number. Could you help me to see where my mistakes are? Here is my code (sorry for my bad english, ill try to improve it):



//Returns an int receiving a char.
int BL :: char2int(char c){
int i=0;
if(c >= '0' && c <= '9'){
i =(int) (c-'0');
}
return i;
}


//Int where the solution is saved, string used.
void BL :: str2int (int &entero, string s){

//Max index of the strings
int const MAX = s.size()-1;

//For first iteration the value is multiplied by 1, second by 10, ...
int multiplier = 1;
entero=0;

//I have doubts if the stop condition is ok..
for(int i=MAX; i>0; i--){
//First iteration
if(multiplier == 1){

//if string's size is 1, index 0 then set the value with char2int
if(MAX == 0){
entero = char2int(s.at(0));
exit(0);
}
//For the rest of sizes
else{
entero+= char2int(s.at(i));

}
}
//Rest of the iterations
else{
entero+= (char2int(s.at(i))*producto);

}
//increasing product
multiplier*=10;
}


}


Aucun commentaire:

Enregistrer un commentaire