Suzane
Suzane

Reputation: 203

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.

Upvotes: 1

Views: 143

Answers (4)

4pie0
4pie0

Reputation: 29734

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!

Upvotes: 0

gled
gled

Reputation: 121

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;

Upvotes: 1

Mats Petersson
Mats Petersson

Reputation: 129464

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

Upvotes: 0

fiscblog
fiscblog

Reputation: 694

By

str.assign(InString);

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

Upvotes: 1

Related Questions