1

This is probably a dumb question but if I have a C++ string as follows,

str = "the cat is black\n"

If I remove the last character, namely '\n', does this leave me with a null terminated string? Does the statement below work in creating a null terminated char * from the original string str?

char *c = str.erase(str.size()-1).c_str();
kometen
  • 6,536
  • 6
  • 41
  • 51
MikeRin
  • 11
  • 5

2 Answers2

5

Yes, std::string::c_str() will always return a null-terminated string.

http://www.cplusplus.com/reference/string/string/c_str/

http://en.cppreference.com/w/cpp/string/basic_string/c_str

Dan Korn
  • 1,274
  • 9
  • 14
  • 1
    Thanks!! I'm understanding that as long as it's a c.str() then the '\0' termination is automatic, – MikeRin Feb 21 '16 at 23:34
0

If it is a C string as for example

char str[] = "the cat is black\n";

you can do this like

str[strcspn( str, "\n" )] = '\0';

If it is an object of type std::string as for example

std::string str( "the cat is black\n" );

you can write

if ( str.back() == '\n' ) str.erase( str.size() - 1 );

or

if ( !str.empty() && str.back() == '\n' ) str.erase( str.size() - 1 );

This statement

const char *c = str.erase( str.size() - 1 ).c_str();
^^^^^

is also valid provided that the string contains the new line character or empty.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335