// Purpose: To demonstrate printing with printf() // Author: Keith Shomper // Date : 9 Oct 2008 #include using namespace std; int main () { string s1; // A C++-style string (a.k.a. a standard string) char s2[80]; // A C-style string (i.e., character array) int i; double d; char c; // Get some values to work with cout << "Please enter a string: "; getline(cin, s1, '\n'); cout << "Please enter an integer: "; cin >> i; cout << "Please enter a floating point value: "; cin >> d; cout << "Please enter a character: "; cin >> c; // Print the string in quotations // Note: the variable s is a C++-style string (a.k.a a standard string) // so it needs to be converted to a C-style string for use with // printf(); we do this with the .c_str() function printf("The string you entered is: \"%s\"\n", s1.c_str()); // Print the integer in various bases and formats printf("The integer %d has the value %o in base 8 (or octal) \n\tand %X in " \ "base 16 (or hexidecimal)\n", i, i, i); printf("The integer %d can also be printed with leading spaces \n\t " \ "like -%5d- and with leading zeros like %05d\n", i, i, i); // Print the double in various formats printf("The double %f when expressed in scientific notation is %e\n", d, d); printf("\tThe number of decimal points can also be controlled as with " \ "currency $%5.2f\n", d); // Print the character in various formats printf("The character %c has the ASCII representation of %u\n", c, c); // Finally, show how a number can be turned into a string using sprintf() by // "printing" an equation to the C-style string s2 sprintf(s2, "%d * %d = %d?\n", i, i, i*i); // Reassign the value of s1 and then concatenate the new string s2 onto s1 // and print the new s1 using the "regular" C++ output object cout s1 = "Did you know that "; s1 += s2; cout << s1; return 0; }