return 0 in converting string to integer

Dec 25, 2012 at 5:48pm
Hi.
I used atoi(string1.c_str()) for convertig a binary string to integer.
but it always return 0.
why?????!!!!1
Dec 25, 2012 at 6:04pm
What do you mean when saying "binary string"? atoi can only convert to int a representattion of an integer number writtten in decimal notation.
Last edited on Dec 25, 2012 at 6:04pm
Dec 25, 2012 at 6:17pm
I mean that in this string we just have 0,1.
Dec 25, 2012 at 6:24pm
It must be that the string was not a valid decimal number. What exactly was the string?

By the way, you can use strtol() to convert a string in any base from 2 to 36 into a long int.

http://www.cplusplus.com/reference/cstdlib/strtol/
Dec 25, 2012 at 6:33pm
I wrote like this:
1
2
3
string number;
cin>>number;
int value=atoi(number.c_str())
Dec 25, 2012 at 6:45pm
Yes, but what does the string contain?
Dec 25, 2012 at 6:45pm
If 'number' does not represent an integer literal then of course you will not get a valid value.
Dec 25, 2012 at 6:48pm
it contains 1 and 0.

edit:
it can get a number between and including 0 and 9
Last edited on Dec 25, 2012 at 7:03pm
Dec 25, 2012 at 9:29pm
May I ask, 1 and 0 like this, "1 0" or " 0 1 " or "10" or what?

it can get a number
what is "it", please?

At any rate, atoi() should be able to handle any string which converts to a valid integer, usually in the range "-2147483648" to "+2147483647". The string "10" certainly fits within that range.

As stated in the reference below, if the input is not a valid integer, the result is zero. http://www.cplusplus.com/reference/cstdlib/atoi/


Last edited on Dec 25, 2012 at 9:30pm
Dec 26, 2012 at 3:55am
How about this?
1
2
int value;
cin >> value;
Dec 26, 2012 at 7:08am
my problem is similar, I have to convert a string to int and strings.

For example, 123TCat and Dog W346 edf fedh are good

assign 123 to x
Cat and dog to str
346 to y
are good to line
Dec 26, 2012 at 5:36pm
usually in the range "-2147483648" to "+2147483647"

ok,it was my problem.
number was out of this range!!
Thank you
Dec 26, 2012 at 5:55pm
Well, that was hard work. I asked three times what was the exact string, and still got no answer. We would have reached the solution much faster if we worked together in cooperation.
Dec 26, 2012 at 6:08pm
ok,I'm sorry!!
Thank you again
Last edited on Dec 26, 2012 at 6:12pm
Topic archived. No new replies allowed.