简体   繁体   中英

Character pointer passed as parameter converting to string

Hi I am new to C++ and I require some input for the following problem:

In my header file (MyClass.h) a function is defined as:

bool Function(char *InString,char *outStr);

This has been implemented in "MyClass.cpp" like this:

bool MyClass::Function(char *InString,char *OutString=0) {
  std::string str = ***** I require the InString to be converted to String and assigned to str.
}

In my main function of console I used the following function:

#include "MyClass.h"
int _tmain(int argc, _TCHAR* argv[]) {
  char inp[50];
  char output[50];
  memset(output,0,sizeof(output));//Intialized
  std::cin>>inp;
  MyClass x;
  bool m = x.Function(inp,output);
}

Any help is deeply appreciated.

By

str.assign(InString);

you can assign a char to a std::string .

You can just assingn the character pointer to the string. As long as the data pointed to by the character pointer is null terminated, the copy will work as expected.

std::string str = InString;

Just std::string str = InString; should work.

well std::string has a constructor for this:

const char *s = "\nHello, World!";
std::string str(s);
cout<<str;

char *s2 = "\nHello, World!";
std::string str2(s2);
cout<<str2;

gives me:

Hello, World!

Hello, World!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM