473,324 Members | 2,257 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,324 software developers and data experts.

String to int

I have an array of char values that I need to assign to a integer variable.
I tried casting it: integer = (int)charArray; but when I run it I get
incorrect results in integer. What is the correct way to cast a string to
an integer?
Jul 19 '05 #1
4 55943
- Steve - wrote:
I have an array of char values that I need to assign to a integer variable.
I tried casting it: integer = (int)charArray; but when I run it I get
incorrect results in integer. What is the correct way to cast a string to
an integer?


As it is somewhat unclear just what you're trying to do, why don't
you post your code?

[hint: casting is likely not what you want]

HTH,
--ag

--
Artie Gold -- Austin, Texas

Jul 19 '05 #2
- Steve - wrote:
I have an array of char values that I need to assign to a integer variable.
I tried casting it: integer = (int)charArray; but when I run it I get
incorrect results in integer. What is the correct way to cast a string to
an integer?


Avoid casts whenever possible. Avoid C-style casts always. This is a
good example of why: the code you tried to use does nothing even
remotely similar to what you want, but the cast prevents the compiler
from warning you of that fact. Had you used a C++ cast operator instead,
you would have found that you needed reinterpret_cast, and that would
have (or should have) served as a warning that it wasn't doing what you
wanted.

Next piece of advice: Don't use char pointers and arrays for strings.
Use std::string. It's much easier to deal with and much less
error-prone. Here's an example of what (I think) you want to do:

#include <iostream>
#include <string>
#include <sstream>

int main()
{
std::string str("4922");
std::istringstream strin(str);
int i;

strin >> i;

std::cout << str << " = " << i << std::endl;

return 0;
}

Think of 'strin' as 'cin' but using the string supplied to it as its
data source, rather than the program's standard input.

-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.

Jul 19 '05 #3

"- Steve -" <se****@foundation.sdsu.edu> wrote in message
news:2c*****************@news1.central.cox.net...
I have an array of char values that I need to assign to a integer variable. I tried casting it: integer = (int)charArray; but when I run it I get
incorrect results in integer. What is the correct way to cast a string to
an integer?


I can only agree with all the things Kevin already said so I won't waste my
breath. I'd just want to point out that a template function will give you
more freedom regarding the conversion you want to achieve:

////////////////////////////////////////////////////////////////////////////
//
template<typename T>
T FromStringEx( const std::string& s, bool& bSuccess)
// string conversion from string to typename T with a flag
// the represents success or failure.
//
// e.g: int d = FromString<int>( s );
//
// if you want to check whether the conversion was successful then you can
// use the bSuccess flag!
////////////////////////////////////////////////////////////////////////////
//
{
bSuccess = true;
std::istringstream is(s);
T t;
is >> t;
if( !is )
bSuccess = false;
return t;
}

HTH
Chris
Jul 19 '05 #4
Tom
"- Steve -" wrote:
I have an array of char values that I need to assign to a integer variable.
I tried casting it: integer = (int)charArray; but when I run it I get
incorrect results in integer. What is the correct way to cast a string to
an integer?


Other folks have answered your question. Let me just add that your
question is answered by Sections 38.2 and 38.3 of the FAQ:

http://www.parashift.com/c++-faq-lit....html#faq-38.2

You may find the rest of the FAQ helpful too.

Also, let me reiterate that it's a bad idea to use an array of chars
instead of a std::string.

Best regards,

Tom
Jul 19 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

16
by: Krakatioison | last post by:
My sites navigation is like this: http://www.newsbackup.com/index.php?n=000000000040900000 , depending on the variable "n" (which is always a number), it will take me anywhere on the site......
5
by: Stu Cazzo | last post by:
I have the following: String myStringArray; String myString = "98 99 100"; I want to split up myString and put it into myStringArray. If I use this: myStringArray = myString.split(" "); it...
9
by: John F Dutcher | last post by:
I use code like the following to retrieve fields from a form: recd = recd.append(string.ljust(form.getfirst("lname",' '),15)) recd.append(string.ljust(form.getfirst("fname",' '),15)) etc.,...
9
by: Derek Hart | last post by:
I wish to execute code from a string. The string will have a function name, which will return a string: Dim a as string a = "MyFunctionName(param1, param2)" I have seen a ton of people...
10
by: Angus Leeming | last post by:
Hello, Could someone explain to me why the Standard conveners chose to typedef std::string rather than derive it from std::basic_string<char, ...>? The result of course is that it is...
2
by: Andrew | last post by:
I have written two classes : a String Class based on the book " C++ in 21 days " and a GenericIpClass listed below : file GenericStringClass.h // Generic String class
4
by: Locusta | last post by:
Hello, I have been struggeling for replacing a string in a string. The snippet from the program below replaces the <, & and > with the XML equivalent values. In the program, I allocate space...
29
by: zoro | last post by:
Hi, I am new to C#, coming from Delphi. In Delphi, I am using a 3rd party string handling library that includes some very useful string functions, in particular I'm interested in BEFORE (return...
4
by: Emilio | last post by:
Question about Shared Sub Connect(server As , message As ) Why is in square brackets? Is it like Shared Sub Connect(server() As String, message() As String)
2
by: Badass Scotsman | last post by:
Hello, Using VB and ASP,NET I would like to be able to search a STRING for a smaller STRING within, based on the characters which appear before and after. For example: String1 = " That was...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.