strgback.cpp 856 B

123456789101112131415161718192021222324252627282930313233
  1. // strgback.cpp -- a function that returns a pointer to char
  2. #include <iostream>
  3. char * buildstr(char c, int n); // prototype
  4. int main()
  5. {
  6. using namespace std;
  7. int times;
  8. char ch;
  9. cout << "Enter a character: ";
  10. cin >> ch;
  11. cout << "Enter an integer: ";
  12. cin >> times;
  13. char *ps = buildstr(ch, times);
  14. cout << ps << endl;
  15. delete [] ps; // free memory
  16. ps = buildstr('+', 20); // reuse pointer
  17. cout << ps << "-DONE-" << ps << endl;
  18. delete [] ps; // free memory
  19. // cin.get();
  20. // cin.get();
  21. return 0;
  22. }
  23. // builds string made of n c characters
  24. char * buildstr(char c, int n)
  25. {
  26. char * pstr = new char[n + 1];
  27. pstr[n] = '\0'; // terminate string
  28. while (n-- > 0)
  29. pstr[n] = c; // fill rest of string
  30. return pstr;
  31. }