Solved

Convert C string to STRING

Posted on 2013-06-08
11
550 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 74

Expert Comment

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

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

Expert Comment

by:phoffric
Comment Utility
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
Comment Utility
Output of program is:
hello world
This is null terminated.
This is null terminated.  hello world

Open in new window

0
 
LVL 1

Author Comment

by:edvinson
Comment Utility
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 74

Expert Comment

by:käµfm³d 👽
Comment Utility
What does the SumOfDigits function have to do with the GetComputerName function?
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 1

Author Comment

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

Expert Comment

by:phoffric
Comment Utility
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
Comment Utility
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
Comment Utility
oh, also I am calling my function like this:

int sum = SumOfDigits(lpszComputer)
0
 
LVL 32

Expert Comment

by:phoffric
Comment Utility
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 32

Accepted Solution

by:
sarabande earned 500 total points
Comment Utility
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

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Suggested Solutions

This article will show you some of the more useful Standard Template Library (STL) algorithms through the use of working examples.  You will learn about how these algorithms fit into the STL architecture, how they work with STL containers, and why t…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

772 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

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now