Monday, May 24, 2010

How do I convert a string to an int in C++? Preferably the hard way..?

Okay, lets say that i have a string id;


Whatever is in the variable id is user entered. So I can't just say int num = atoi("pat");





and id MUST be a string.





if i wanted to do:


num = atoi(id);





How do I do this conversion without getting this error when compiling:


error: cannot convert `std::string' to `const char*' for


argument `1' to `int atoi(const char*)'





any other way is fine that isn't too complicated. I just want the value of the string to be an int.

How do I convert a string to an int in C++? Preferably the hard way..?
Try int i = atoi(id.c_str());
Reply:The best and least error prone way is to go through each character one by one and look at the ascii code.





If you try to convert the letter 'a' for example to an integer you will have problems, so look at it's ascii value in order to not cause a runtime error.





If the ascii value does not equal the ascii values for the numbers 0-9 then it is not a valid integer and an exception should be thrown.





chars = myString.c_str();





for(i=0; i%26lt; chars.length ; i++)


{


if(chars[i] %26gt; 48 %26amp;%26amp; chars[i] %26lt; 58)


{


convert to int here;


}


}





then you will want to multiply each of the result ints by the appropriate multiple of 10.





if these are your ints





3


4


2


5


= 3,425 (int)





you need to do this





completeInt = (3*1000) + (4*100) + (2*10) + 5;





this will give you the int you desire.





This whole approach might seem unnecessary but,if you don't check to see if they are not letter or symbols first, you will have problems in the future.
Reply:What the first answerer said would work. Or take a look at http://forums.devshed.com/showpost.php?p... , especially at the part where stringstreams are used. Use a stringstream to take in a string, and force it to output to an int. If it succeeds, the conversion was successful.





What I don’t recommend you do is attempt what El Gordo has done. The best and least error prone way is to use pre-written code, especially one that has been written and tested by extremely smart people, like say, the ones who made your compiler. There is a way to do it with standard C++ or C functions, so rely on them.
Reply:You can get rid of your compile error by using the c_str() function to convert the std::string to a const char*. num = atoi(myString.c_str()).





I think you need to do more checking of the user input string, though. Read up on what atoi does when it's handed a string that contains characters that are not numbers. You probably need to analyze the string before just passing it to atoi(), try writing your own function IsNum(char ) and pass each letter to this function. If one of them is not a number, display an error message to the user. If all letters pass, then call atoi( ).


No comments:

Post a Comment