简体   繁体   中英

How to assign char* (with every possible value) to C++ string

I'm in C++. And I'm trying to append a char array to a C++ string. The only thing is that this array can have every possible value, negative, positive and 0. So when I assign this array to the string, it stops at some point because it found a 0 value.
1) Can string append these values? Or do they have to be strictly from 1 to 127? If true,
2) Is there a way to keep the string assignment going even even if it finds a 0?

The string::append( const char* s, size_t n ) overload for append() should do what you want. Assuming that cpp_string is your std::string variable or reference and c_string_ptr is your pointer to an array of characters:

cpp_string.append( c_string_ptr, number_of_bytes);

Note however, the std::string is a typedef for std::basic_string<char> . Since char might not be signed on your platform you might not get the comparison behavior you want. You should ensure that char is signed on your platform or you might want to use your own typedef to prevent problems if the platform (or build) changes in the future:

typedef std::basic_string<signed char> sstring;  // or whatever name you like

Use string::append() function.

Code Example:

#include <iostream>
#include <string>
using namespace std;

int main ()
{
  string str2="My String";

  str.append("is nice",7);

  cout << str << endl;
  return 0;
}

Is there a way to keep the string assignment going even even if it finds a 0?
character arrays are null terminated, and use 0 to determine the end of array.
std::string does not use 0 to determine end of string.

You can use the following functions:

string& append ( const char* s, size_t n );

string& append ( const char* s );

The first one will append with the char* until it reach the size, the second will append until it found a \\0 int the string.

So you can use the first with any value of chars, but you have to take care with the second since (char)0 will terminates the appending.

See: http://www.cplusplus.com/reference/string/string/append/

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