Problem with converting CString to Int

Hey,I am having problems with converting a CString to an int and than doing checks on the int to see if it is in a particualr range. Below is a general idea of what I am doing.

1
2
3
4
5
6
7
8
CString numstr = "28"
int num = atoi(numstr);
BOOL valid = TRUE;
if(num < -32,768)
{
  valid = FALSE;
}


For some reason when running the above code the if statement is executed but it should not be becasue 28 is not less than -32,768. Do anyone know why this is happening, I am not seeing the reason for this at all!! The num variable is being assigned the correct value. Any help will be greatly appreciated.
Decimal separator in C++ is dot (.), not comma (,).
Comma is another operator which evaluates its operands left-to-rigth and returns result of right one
So your if statement actually:
if( (num < -23),(768) )
Result of left operand is discarded and right is returned: if( 768 ), Which is always true.
If you wanted to separate not decimal part, but thousands part, do not do that. All numbers should be written without any separators.
closed account (3qX21hU5)
Hmm do you mean the Microsoft specific CString? or Just c-style strings?

Anyways use stringstreams to convert it into a integer.

First read in the c-style string into the string stream, then write whatever is in the stream to the int or int's.

Depending on what you have in your c-string is it can be as easy as this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <sstream>      // Need this for stringstreams

using namespace std;

int main()
{
    char *number = "12345";

    stringstream convert;

    convert << number;

    int intNumber;

    convert >> intNumber;

    cout << intNumber + 500;

    return 0;
}


Though I just have to say, I would highly highly suggest you get away from c strings as fast as possible when using C++. 99.99% of the time you should use std::string.

Also remember we are using C++ not C so get away from atoi() also and use stringstreams.
Last edited on
CString is a Microsoft C++/CLI class.
When writing numbers, avoid using separators.
Just write your number as "32768" and not as "32,768".
MiiNiPaa did tell you more about it but didn't tell you the right solution anyways, because there are no floating-point numbers around, and 32768 should be (0xFFFF>>1) ?
L B wrote:
CString is a Microsoft C++/CLI class.
No, it's an ATL/MFC class http://msdn.microsoft.com/en-us/library/vstudio/ms174288.aspx

@tnjgrahm
I think you can use atoi with CSting to convert it.
Topic archived. No new replies allowed.