Std::string::c str

From aldeid
Jump to: navigation, search

Syntax

const char* c_str() const;

Description

Get C string equivalent

Returns a pointer to an array that contains a null-terminated sequence of characters (i.e., a C-string) representing the current value of the string object.

This array includes the same sequence of characters that make up the value of the string object plus an additional terminating null-character ('\0') at the end.

Parameters

none

Return Value

A pointer to the c-string representation of the string object's value.

Example

This function can be used to return a pointer to a string corresponding to a file path, as shown below:

Source Run
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
  string const fn("test.txt");
  ofstream fs(fn.c_str());
  if (!fs) perror("Error creating stream");

  fs << "This is a test" << endl;

  return 0;
}
$ ./main 
$ cat test.txt
This is a test