C++ Examples
Dave Braunschweig
Strings
#include <algorithm> #include <iostream> #include <string> using namespace std; string toLower(string); string toUpper(string); int main() { string str = "Hello"; cout << "string: " << str << endl; cout << "tolower: " << toLower(str) << endl; cout << "toupper: " << toUpper(str) << endl; cout << "string.find('e'): " << str.find('e') << endl; cout << "string.length(): " << str.length() << endl; cout << "string.replace(0, 1, \"j\"): " << str.replace(0, 1, "j") << endl; cout << "string.substr(2, 2): " << str.substr(2, 2) << endl; string name = "Bob"; double value = 123.456; cout << name << " earned $" << fixed << setprecision (2) << value << endl; } string toLower(string str) { transform(str.begin(), str.end(), str.begin(), ::tolower); return str; } string toUpper(string str) { transform(str.begin(), str.end(), str.begin(), ::toupper); return str; }
Output
string: Hello tolower: hello toupper: HELLO string.find('e'): 1 string.length(): 5 string.replace(0, 1, "j"): jello string.substr(2, 2): ll Bob earned $123.46
Files
// This program demonstrates reading a text file with error handling. // References: // https://en.wikibooks.org/wiki/C%2B%2B_Programming #include <fstream> #include <iostream> #include <string> using namespace std; void readFile(string); int main() { string FILENAME = "temperature.txt"; readFile(FILENAME); } void readFile(string filename) { fstream file; string line; file.open(filename, fstream::in); if (file.is_open()) { while (getline(file, line)) { cout << line << endl; } file.close(); } else { cout << "Error reading " << filename << endl; } }
Output
Celsius,Fahrenheit 0,32 10,50 20,68 ... 80,176 90,194 100,212