简体   繁体   English

字符指针作为参数传递给字符串

[英]Character pointer passed as parameter converting to string

Hi I am new to C++ and I require some input for the following problem: 嗨,我是C ++的新手,我需要一些输入以解决以下问题:

In my header file (MyClass.h) a function is defined as: 在我的头文件(MyClass.h)中,一个函数定义为:

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

This has been implemented in "MyClass.cpp" like this: 这已在“ MyClass.cpp”中实现,如下所示:

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 . 您可以将一个char分配给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; 只是std::string str = InString; should work. 应该管用。

well std::string has a constructor for this: std::string为此有一个构造函数:

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! 你好,世界!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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