Advertisement
SepandMeenu

C++ string to C-string conversion

Jun 4th, 2019
245
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.72 KB | None | 0 0
  1. // strings and c-strings
  2. // tested with g++ (Debian 6.3.0-18+deb9u1) 6.3.0 20170516 under Debian Stretch
  3. #include <iostream>
  4. #include <string>
  5.  
  6. using std::cout;
  7. using std::endl;
  8.  
  9. std::string mk_str() {
  10.   return ">Karl-Heinz-Rumpelstilzchen-Koopmann-van-Wijdenvouwrden-123&456*&^%#:";
  11. }
  12.  
  13. int main ()
  14. {
  15.   std::string str = mk_str();  // initial string
  16.   const char* cstr = str.c_str();  // notice the `const` qualifier
  17.  
  18.   cout << "--- TEST ---" << endl;
  19.   cout << "  string = '" << str << "'" << endl;
  20.   cout << "c-string = '" << cstr << "'" << endl;
  21.  
  22.   for(std::size_t i = 0; i <= str.length(); ++i)
  23.     printf("char %3d = '%c'\n", int(cstr[i]), cstr[i]);
  24.  
  25.   cout << "--- END TEST ---" << endl;
  26.   return 0;
  27. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement