| | |
Conversion from Char* to int ?
Please support our C++ advertiser: Intel Parallel Studio Home
Thread Solved |
•
•
Join Date: Jun 2007
Posts: 275
Reputation:
Solved Threads: 45
What exactly do you mean?
Do you
a) want to convert an array of ASCII characters into an int:
b) convert the pointer to an int:
Do you
a) want to convert an array of ASCII characters into an int:
C++ Syntax (Toggle Plain Text)
char *numstr = "1234"; int val = atoi(numstr); // val now = 1234
b) convert the pointer to an int:
C++ Syntax (Toggle Plain Text)
char *xyz; // given contents somewhere int addr = (int)xyz; // addr now = the char pointer
Don't use atoi() - here's how to do it in C++ The reason for using stringstreams is that your conversion will fail if the string contains anything which can't be converted to an int - which, if you're dealing with user input, is a real problem. if you use a stringstream, you can detect the error, without it messing up the rest of the program.
CPP Syntax (Toggle Plain Text)
#include <sstream> #include <iostream> int main() { const char* foo("1234"); std::stringstream ss(foo); int i; if( ss >> i ) std::cout << "i is: " << i ; else std::cout << "error"; }
¿umop apisdn upside down? I suppose I should add that atoi() has no reliable way of handling any errors that might be thrown up when your conversion fails. This is where stringstreams provide a far more robust solution, that you can test for failure before using the retrieved value.
Last edited by Bench; Jul 19th, 2007 at 9:59 am.
¿umop apisdn upside down? ![]() |
Similar Threads
- how to convert char to int (C++)
- Convertings strings to numbers (C++)
- char+int????? (C++)
- Minor problem (C)
- help with IsNumeric function (C++)
- adding data into an char array (C++)
Other Threads in the C++ Forum
- Previous Thread: Can not enter multiple data into nested while loop
- Next Thread: Quick question
| Thread Tools | Search this Thread |
api array arrays beginner binary bitmap bmp c++ c/c++ calculator char class classes code compile compiler console conversion count data delete desktop directshow dll download dynamic encryption error file forms fstream function functions game getline givemetehcodez google graph gui homeworkhelper iamthwee ifstream input int integer java lib library linkedlist linker linux loop looping loops map math matrix memory newbie news node number output parameter pointer problem program programming project proxy python random read recursion recursive return string strings struct studio temperature template templates test text text-file tree unix url variable vector video visual visualstudio win32 windows winsock word wordfrequency wxwidgets






