C++/String/string data

Материал из C\C++ эксперт
Перейти к: навигация, поиск

Passing Arguments by Value

<source lang="cpp">

  1. include <iostream>
  2. include <string>

using namespace std; void printMessage(string); int main () {

  string str;
  cout << "Enter a string: ";
  cin >> str;
  printMessage(str); 
  return 0;

} void printMessage (string s) {

  cout << "You inputted " << s;

}


 </source>


Use char pointer to point to the char array returned from string.data()

<source lang="cpp">

  1. include <iostream>

using std::cout; using std::endl;

  1. include <string>

using std::string; int main() {

  string string1( "STRINGS" );
  const char *ptr1 = 0;
  ptr1 = string1.data();
  for ( int i = 0; i < string1.length(); i++ )
     cout << *( ptr1 + i ); // use pointer arithmetic
  return 0;

} /* STRINGS

*/        
   
 </source>