Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Convert C string to STRING

Posted on 2013-06-08
11
Medium Priority
?
577 Views
Last Modified: 2013-06-13
I have a regular szMyString ( 0 terminated ) and I need to convert it to a STRING.

Is there a simple way to do this?
0
Comment
Question by:edvinson
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 4
  • 2
  • +1
11 Comments
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 39232471
Have you tried the overloaded string constructor?

http://www.cplusplus.com/reference/string/string/string/
0
 
LVL 32

Expert Comment

by:phoffric
ID: 39232524
This example shows several mechanisms to convert a null character c-style string into a C++ string:
#include <iostream>
using namespace std;

int main() {
  const char * pStr = "hello world"; // null terminated c-string
  string myStr(pStr);     // construct C++ string from c-string
  cout << myStr << endl;

  char szMyCstring[] = "This is null terminated.  ";
  myStr = szMyCstring;    // assignment operator
  cout <<  myStr << endl;

  myStr += pStr;    // appends C-style string to string
  cout <<  myStr << endl;
}

Open in new window

See:  c-string (2)  string& operator= (const char* s);
http://www.cplusplus.com/reference/string/string/operator=/

See: c-string (2)  string& operator+= (const char* s);
"Append to string
"Extends the string by appending additional characters at the end of its current value"
http://www.cplusplus.com/reference/string/string/operator+=/
0
 
LVL 32

Expert Comment

by:phoffric
ID: 39232527
Output of program is:
hello world
This is null terminated.
This is null terminated.  hello world

Open in new window

0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
LVL 1

Author Comment

by:edvinson
ID: 39232532
For my problem , I can't get it to work

Here is the function I have:

/*
* Return Sum of Digits in a String
*
* @param     string    string     string to parse for digits to return SUM
* @return    int       sum        returns sum of digits present in string param
*/
int SumOfDigits(string text){
    
    int sum = 0;
    
    for (size_t i=0; i< text.size(); ++i){
        const char character = text[i];
        if( isdigit(character)){
            char digitBuf[2] = { character, '\0' };
            sum += atoi(digitBuf);    
        }    
    }   
    return sum;
}

Open in new window


and I WANT to pass it this:

GetComputerName(lpszComputer,&dComputer);  

Open in new window


When I use lpszComputer, I get errors.

I tried converting it, but still getting error. Where am I going wrong?

lpszComputer holds the value "OWNER_44538837", in case you need that
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 39232554
What does the SumOfDigits function have to do with the GetComputerName function?
0
 
LVL 1

Author Comment

by:edvinson
ID: 39232567
I am passing it the return value, which is stored in lpszComputer
0
 
LVL 32

Expert Comment

by:phoffric
ID: 39232578
Please show your exact declaration of GetComputerName so that we can see the return type.

>> and I WANT to pass it this
it is SumOfDigits , right? If so, then is this your line of code:
         int sum = SumOfDigits( GetComputerName(lpszComputer,&dComputer) );

>> When I use lpszComputer, I get errors.
Please show the line of code where you get an error, and please post the exact error message.
0
 
LVL 1

Author Comment

by:edvinson
ID: 39232580
sure, here is how I declared the values to be used in GetComputerName:

TCHAR  lpszComputer[255];
DWORD dComputer = sizeof(lpszComputer);

Open in new window

0
 
LVL 1

Author Comment

by:edvinson
ID: 39232584
oh, also I am calling my function like this:

int sum = SumOfDigits(lpszComputer)
0
 
LVL 32

Expert Comment

by:phoffric
ID: 39232629
You should post the exact error message and the line in error. I assume the line in error is:
    int sum = SumOfDigits(lpszComputer)
because SumOfDigits expects a string arg, but you are providing a TCHAR[] arg.
So, first convert lpszComputer to a string, which is possible if TCHAR is defined as a char *. But TCHAR may be defined differently depending upon your project configuration.

Please look at "converting TCHAR to string"

Ref: TCHAR is either char or wchar_t, depending on the value of _UNICODE:
// abridged from tchar.h
#ifdef _UNICODE
   typedef wchar_t TCHAR;
   #define __T(x) L ## x
#else
  typedef char TCHAR;
  #define __T(x) x
#endif

Open in new window


Ref: Convert TCHAR array to std::string
you have a (potential) problem with character size - TCHAR is either char or wchar_t depending on whether you're doing a Unicode build or an ANSI build, while std:Tongue Tiedtring is always a string of char.
I don't know how you are configured, but this may work:
string lpszComputerString = lpszComputer;
int sum = SumOfDigits(lpszComputerString ) ;

If that does not work, then from the last above reference is this quote:
Simple solution: open your project properties, go to Configuration Properties -> General and flip the Character Set setting to Multi-byte. See also
http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=849851&SiteID
0
 
LVL 35

Accepted Solution

by:
sarabande earned 2000 total points
ID: 39238284
to add to before comment:

if you want to use std::string you should try to avoid TCHAR type. as told by phoffric TCHAR was mapped to either char or wchar_t while std::string is always char.

you can see the current mapping of TCHAR in the project properties - configuration properties - general page. here the property 'Character  Set' either was set to 'multi-byte' or to 'unicode'. i wouldn't make a switch in your code depending on _UNICODE as suggested. _UNICODE is a macro used by former versions of visual studio. the current macro used is UNICODE. the _UNICODE was still supported for compatibility reasons, hence, you could make a preprocessor switch with #ifdef UNICODE or #ifdef _UNICODE and it would work. but surely it also makes your code ugly and it makes less sense to always support duplicate code for any string handling.

you either would use MFC CString instead of std::string as CString is also dependent on the UNICODE-MULTIBYTE switch.

int SumOfDigits(CString text){
    int sum = 0;
    for (int i=0; i< text.GetLength(); ++i){
        TCHAR character = text[i];
        if( isdigit(character)){
             sum += (character - TCHAR('0'));
             ...

Open in new window


for both char or wchar_t you could replace the conversion with atoi by simply subtracting '0' character from recognized digit.

however, if you don't need UNICODE at all, a much more simpler solution simply is to change the character set from UNICODE to MULTIBYTE and your current code should compile.

a further way is to convert the computername from wide characters to ansi characters.

WCHAR * wszComputerName[256] = { 0 };
DWORD   dSize = 256;
if (GetComputerName(wszComputerName, &dSize))
{
      char szComputerName[256] = { '\0' };
      wcstombs(szComputerName, sizeof(szComputerName), wszComputerName);
      int sum = SumOfDigits(szComputerName);
      ....

Open in new window


Sara
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In days of old, returning something by value from a function in C++ was necessarily avoided because it would, invariably, involve one or even two copies of the object being created and potentially costly calls to a copy-constructor and destructor. A…
Templates For Beginners Or How To Encourage The Compiler To Work For You Introduction This tutorial is targeted at the reader who is, perhaps, familiar with the basics of C++ but would prefer a little slower introduction to the more ad…
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.

722 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question