fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4.  
  5. struct person
  6. {
  7. std::string firstName;
  8. std::string middleName;
  9. std::string lastName;
  10. std::string streetAddress1;
  11. std::string streetAddress2;
  12. std::string city;
  13. std::string state;
  14. std::string zip;
  15. static std::string GetPrintfFormatString()
  16. {
  17. static const char FormatString[] = R"(
  18. First Name: %s
  19. Middle Name: %s
  20. Last Name: %s
  21. Street Address 1: %s
  22. Street Address 2: %s
  23. City: %s
  24. State: %s
  25. Zip: %s
  26. )";
  27. return FormatString;
  28. }
  29. };
  30.  
  31. void PrintPersonWithPrintf(const person& p)
  32. {
  33. ::printf(
  34. p.GetPrintfFormatString().c_str(),
  35. p.firstName.c_str(), p.middleName.c_str(), p.lastName.c_str(),
  36. p.streetAddress1.c_str(), p.streetAddress2.c_str(),
  37. p.city.c_str(), p.state.c_str(), p.zip.c_str());
  38. }
  39.  
  40. void PrintPersonWithSPrintf(const person& p)
  41. {
  42. std::string formatString = p.GetPrintfFormatString();
  43. size_t outputLen = formatString.length() + p.firstName.length()
  44. + p.middleName.length() + p.lastName.length()
  45. + p.streetAddress1.length() + p.streetAddress2.length()
  46. + p.city.length() + p.state.length() + p.zip.length()
  47. + 20;
  48. std::vector<char> buffer(outputLen, 0);
  49. ::sprintf(
  50. buffer.data(), formatString.c_str(),
  51. p.firstName.c_str(), p.middleName.c_str(), p.lastName.c_str(),
  52. p.streetAddress1.c_str(), p.streetAddress2.c_str(),
  53. p.city.c_str(), p.state.c_str(), p.zip.c_str());
  54. std::string out = buffer.data();
  55. std::cout << out;
  56. }
  57.  
  58. int main()
  59. {
  60. person me{
  61. "Benjamin",
  62. "Eugene",
  63. "Key",
  64. "12343 Some Street",
  65. "Apt 826",
  66. "Austin",
  67. "Texas",
  68. "78729"
  69. };
  70. PrintPersonWithPrintf(me);
  71. PrintPersonWithSPrintf(me);
  72. return 0;
  73. }
  74.  
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
First Name: Benjamin
Middle Name: Eugene
Last Name: Key
Street Address 1: 12343 Some Street
Street Address 2: Apt 826
City: Austin
State: Texas
Zip: 78729

First Name: Benjamin
Middle Name: Eugene
Last Name: Key
Street Address 1: 12343 Some Street
Street Address 2: Apt 826
City: Austin
State: Texas
Zip: 78729