Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Convert C string to STRING

Posted on 2013-06-08
11
Medium Priority
?
586 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
  • 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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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

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.

Question has a verified solution.

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

Introduction This article is a continuation of the C/C++ Visual Studio Express debugger series. Part 1 provided a quick start guide in using the debugger. Part 2 focused on additional topics in breakpoints. As your assignments become a little more …
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

972 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