In C++ cin >> bzw. cout << für Standard–Eingabe (Tastatur) bzw. Standard–Ausgabe (Bild–Schirm)
#include <iostream> // C++ std I/O functions using namespace std; // declare namespace int main() { double a, b, c; cin >> a >> b >> c; // input: 3 doubles werden gelesen // output cout << a << ", " << b << ", " << c << endl; // Expliziter Zeilenvorschub mit endl }
// Programm readdouble #include <iostream> // C++ std I/O functions using namespace std; // declare namespace int main() { double x, sum = 0.; int n = 0; // Lese Zahlen von Standard-input bis abgebrochen wird (--> cin >> x ergibt false) while ( cin >> x ) { sum += x; // summiere Werte n++; // zaehle Werte } }
#include <iostream> // C++ std I/O functions #include <fstream> // C++ file I/O functions using namespace std; // declare namespace int main() { ifstream inf("eingabe.dat"); // File fuer Eingabe oeffnen ofstream outf("ergebnis.dat"); // File fuer Ausgabe oeffnen double x, sum = 0.; int n = 0; // Lese Zahlen aus Datei bis Datei-ende wird (--> inf >> x ergibt false) while ( inf >> x ) { // statt cin jetzt inf sum += x; // summiere Werte n++; // zaehle Werte outf << x << ", " << sum << ", " << n << endl; // Ausgabe in Datei, outf statt cout } }
Zur Formatierung gibt es in C++ die I/O Manipulatoren, damit kann Breite der Felder, Darstellungsart, Ausrichtung, u.v.a angegeben werden.
Die häufigsten Manipulatoren:
Manipulator | Wirkung | Betrifft |
dec | Dezimaldarstellung | ganze Zahlen |
hex | Hexadezimaldarstellung | dto |
oct | Oktaldarstellung | dto |
scientific | exponentialdarst. 1.2345e2 | Gleitkomma |
fixed | ohne exponent 123.45 | dto |
setprecision(int n) | n Nachkommastellen | dto |
setw(int n) | minimale Ausgabebreite | alle |
left | linksbündig | dto |
right | rechtsbündig | dto |
// print Fahrenheit->Celsius conversion table #include <iostream> #include <iomanip> using namespace std; // declare namespace int main() { int lower(0), upper(300), step = 20; double fahr = 0., celsius; while ( fahr <= upper ) { celsius = (5.0/9.0) * (fahr-32.0); // rechnen ... // cout << fahr << " " << celsius << endl; // ausgeben ... cout << fixed << setw(6) << setprecision(0) << fahr // formatiert ausgeben << setw(10) << setprecision(3) << celsius << endl; fahr += step; } // end-while } // end-main /* Ausgabe: 0 -17.778 20 -6.667 40 4.444 ... */