I was wondering if there's a way to convert a CString or a char *x[10] to a int? I know I can convert int to CString, but can it go the other way?
Thanx,
Atrus

Dani AI

Generated

Short summary tied to the thread: was right that simple C functions (like atoi) or C++ stream parsing work, and 's LPCTSTR cast shows a common quick fix. Important caveats were not shown earlier: atoi gives no error/overflow feedback, and casting CString to LPCTSTR only yields a narrow const char* in ANSI builds — in Unicode builds LPCTSTR is const wchar_t*, so passing it to narrow APIs will fail.

Safer, modern options:

#include <string>
#include <vector>

std::vector<std::string> arr = {"123"};
try {
  int n = std::stoi(arr[0]);            // throws invalid_argument or out_of_range
} catch (const std::invalid_argument&) {
  // not a number
} catch (const std::out_of_range&) {
  // value too large
}

For C-style parsing with explicit error checks, use strtol and errno plus the endptr to detect partial/failed parses and overflow (strtol docs). std::stoi and related helpers are available in C++11+ ().

Notes specific to this thread: the char *str[5]; str[0] = "123"; pattern assigns a string literal — string literals are really const char[], so prefer const char* or, better, std::string/std::vector<std::string> to avoid deprecated/unsafe conversions. For MFC CString keep in mind Unicode vs ANSI: either convert the CString to a narrow buffer before calling narrow C APIs, or call the wide version of the parser (or use generic-text mappings). See the MFC CString reference for details ().

Quick troubleshooting checklist: trim whitespace, verify the entire string was consumed (use endptr or check exceptions), handle sign/base/locale, and check for range/overflow before casting to int.

Recommended Answers

All 7 Replies

Sure, why not?

atoi for converting a char * to an int C or Or stringstreams for C++

for CString (I assume you mean Microsoft MFC CString class)

// convert from CString to int just requires typcasting the CString
CString str = "123";
int n = atoi((LPCTSTR)str);

// convert from int to CString
str.Format("%d", n);

ok so would the following statement work then?

char *str[5];
str[0] = "123";
int n = atoi((LPCTSTR)str[0]);

and yes I meant MFC CStrings... Sorry I didn't mentionthat

When in doubt, test it out!

yeah I thought of that AFTER I posted :P

ok so would the following statement work then?

char *str[5];
str[0] = "123";
int n = atoi((LPCTSTR)str[0]);

you don't need to typecast character arrays -- that typecast is to convert a CString object to const char*.

char *str[5];
str[0] = "123";
int n = atoi(str[0]);
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.