C++ Formatierung, Datei-E/A und Namensräume

C++C++Beginner
Jetzt üben

💡 Dieser Artikel wurde von AI-Assistenten übersetzt. Um die englische Version anzuzeigen, können Sie hier klicken

Einführung

In diesem Lab lernst du die Formatierung, die Datei-E/A und den Namensraum in C++. Du wirst lernen, wie du die Ausgabe formatierst, wie du die Eingabe formatierst, wie du Dateien lesen und schreiben und wie du Namensräume verwendest.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL cpp(("C++")) -.-> cpp/IOandFileHandlingGroup(["I/O and File Handling"]) cpp(("C++")) -.-> cpp/StandardLibraryGroup(["Standard Library"]) cpp(("C++")) -.-> cpp/SyntaxandStyleGroup(["Syntax and Style"]) cpp/IOandFileHandlingGroup -.-> cpp/output("Output") cpp/IOandFileHandlingGroup -.-> cpp/user_input("User Input") cpp/IOandFileHandlingGroup -.-> cpp/files("Files") cpp/StandardLibraryGroup -.-> cpp/string_manipulation("String Manipulation") cpp/SyntaxandStyleGroup -.-> cpp/code_formatting("Code Formatting") subgraph Lab Skills cpp/output -.-> lab-178541{{"C++ Formatierung, Datei-E/A und Namensräume"}} cpp/user_input -.-> lab-178541{{"C++ Formatierung, Datei-E/A und Namensräume"}} cpp/files -.-> lab-178541{{"C++ Formatierung, Datei-E/A und Namensräume"}} cpp/string_manipulation -.-> lab-178541{{"C++ Formatierung, Datei-E/A und Namensräume"}} cpp/code_formatting -.-> lab-178541{{"C++ Formatierung, Datei-E/A und Namensräume"}} end

Inhaltsvorschau

Verwende <iomanip>-E/A-Manipulatoren für die Formatierung von Eingabe und Ausgabe.

Der <fstream>-Header liefert ifstream (Eingabedateistrom) und ofstream (Ausgabedateistrom) für die Datei-Eingabe und -Ausgabe.

  • Formatierung von Eingabe und Ausgabe
  • Datei-Eingabe und -Ausgabe
  • Namensraum

Formatierung von Eingabe/Ausgabe mit E/A-Manipulatoren (Header )

Der <iomanip>-Header liefert sogenannte E/A-Manipulatoren zur Formatierung von Eingabe und Ausgabe:

  • setw(int field-widht): Legt die Feldbreite für die nächste E/A-Operation fest. setw() ist nicht klebend und muss vor jeder E/A-Operation angegeben werden. Die Feldbreite wird nach jeder Operation auf den Standardwert zurückgesetzt (mit genau genug Breite, um das Feld aufzunehmen).
  • setfill(char fill-char): Legt das Ausfüllzeichen für die Ausfüllung auf die Feldbreite fest.
  • left|right|internal: Legt die Ausrichtung fest
  • fixed/scientific (für Gleitkommazahlen): Verwenden Sie die Dezimaldarstellung (z.B. 12.34) oder die wissenschaftliche Notation (z.B. 1.23e+006).
  • setprecision(int numDecimalDigits) (für Gleitkommazahlen): Geben Sie die Anzahl der Nachkommastellen an.
  • boolalpha/noboolalpha (für bool): Zeigen Sie bool-Werte als alphabetische Zeichenkette (true/false) oder 1/0 an.
/* Test Formatting Output */
#include <iostream>
#include <iomanip>    // Needed to do formatted I/O
using namespace std;

int main() {
   // Floating point numbers
   double pi = 3.14159265;
   cout << fixed << setprecision(4); // fixed format with 4 decimal places
   cout << pi << endl;
   cout << "|" << setw(8) << pi << "|" << setw(10) << pi << "|" << endl;
      // setw() is not sticky, only apply to the next operation.
   cout << setfill('-');
   cout << "|" << setw(8) << pi << "|" << setw(10) << pi << "|" << endl;
   cout << scientific;  // in scientific format with exponent
   cout << pi << endl;

   // booleans
   bool done = false;
   cout << done << endl;  // print 0 (for false) or 1 (for true)
   cout << boolalpha;     // print true or false
   cout << done << endl;
   return 0;
}

Ausgabe:

3.1416
|  3.1416|    3.1416|
|--3.1416|----3.1416|
3.1416e+00
0
false
image desc
/* Test Formatting Input */
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;

int main() {
   string areaCode, phoneCode;
   string inStr;

   cout << "Enter your phone number in this format (xxx)xxx-xxxx : ";
   cin.ignore();   // skip '('
   cin >> setw(3) >> areaCode;
   cin.ignore();   // skip ')'
   cin >> setw(3) >> phoneCode;
   cin.ignore();   // skip '-'
   cin >> setw(4) >> inStr;
   phoneCode += inStr;

   cout << "Phone number is (" << areaCode << ")"
        << phoneCode.substr(0, 3) << "-"
        << phoneCode.substr(3, 4) << endl;
   return 0;
}

Ausgabe:

Enter your phone number in this format (xxx)xxx-xxxx :  254 845 9946
Phone number is (254)845-9946
image desc

Datei-Eingabe/Ausgabe

Um die Datei-Eingabe und -Ausgabe zu testen, erstelle zunächst eine Datei namens in.txt und schreibe einige ganze Zahlen darin, getrennt durch Leerzeichen. Nach der Ausführung wird das Ergebnis der Berechnung in eine Datei out.txt geschrieben.

/* Test File I/O
   Read all the integers from an input file and
   write the average to an output file        */
#include <iostream>
#include <fstream>   // file stream
#include <cstdlib>
using namespace std;

int main() {
   ifstream fin;   // Input stream
   ofstream fout;  // Output stream

   // Try opening the input file
   fin.open("in.txt");
   if (!fin.is_open()) {
      cerr << "error: open input file failed" << endl;
      abort();  // Abnormally terminate the program (in <cstdlib>)
   }

   int sum = 0, number, count = 0;
   while (fin >> number) {
      // Use >> to read
      cout << number << " ";
      sum += number;
      ++count;
   }
   double average = double(sum) / count;
   cout << "Count = " << count << " average = " << average << endl;
   fin.close();

   // Try opening the output file
   fout.open("out.txt");
   if (!fout.is_open()) {
      cerr << "error: open output file failed" << endl;
      abort();
   }
   // Write the average to the output file using <<
   fout << average;
   fout.close();
   return 0;
}

Ausgabe:

12 15 35 26 68 Count = 5 average = 31.2
image desc

Programmhinweise:

  • Sobald die Datei geöffnet ist, können Sie >> und << für die Eingabe und Ausgabe verwenden, ähnlich wie cin >> und cout <<. (Erweiterte Notiz: ifstream ist eine Unterklasse von istream, zu der cin gehört. ofstream ist eine Unterklasse von ostream, zu der cout gehört.)
  • Ähnlich wie bei der Konsole können auch E/A-Manipulatoren wie fixed, setprecision() und setw() auf den Dateistreams angewendet werden.

Namensraum

Wenn Sie verschiedene Bibliotheksmodule verwenden, besteht immer das Risiko von Namenskollisionen, da unterschiedliche Bibliotheken möglicherweise den gleichen Namen für verschiedene Zwecke verwenden. Dieses Problem kann in C++ durch die Verwendung von Namensräumen gelöst werden. Ein Namensraum ist eine Sammlung von Identifikatoren im gleichen Namensbereich. (In UML und Java wird es als Paket bezeichnet.) Der Name der Entität innerhalb eines Namensraums wird durch den Namensraumnamen qualifiziert, gefolgt von :: (der als Bereichsauflösungsoperator bekannt ist), in der Form namespace::entityName.

Um eine Entität in einen Namensraum zu platzieren, verwenden Sie das Schlüsselwort namespace wie folgt:

// create a namespace called myNamespace for the enclosed entities
namespace myNameSpace {
   int foo;               // variable
   int f() { ...... };    // function
   class Bar { ...... };  // compound type such as class and struct
}

// To reference the entities, use
myNameSpace::foo
myNameSpace::f()
myNameSpace::Bar

Ein Namensraum kann Variablen, Funktionen, Arrays und zusammengesetzte Typen wie Klassen und Strukturen enthalten.

#include <iostream>

namespace a {   // contains variables
   int i1 = 8;
   int i2 = 9;
}

namespace b {   // contains function
   int max(int n1, int n2) {
      return (n1 > n2)? n1 : n2;
   }
}

int main() {
   std::cout << a::i1 << std::endl;                // 8
   std::cout << b::max(a::i1, a::i2) << std::endl; // 9
}

Ausgabe:

8
9
image desc

Verwendung von Namensräumen

// Use the fully qualified names,
// such as std::cout, std::endl, std::setw() and std::string.
std::cout << std::setw(6) << 1234 << std::endl;

// Use a using declaration to declare the particular identifiers.
using std::cout;
using std::endl;
......
cout << std::setw(6) << 1234 << endl;

// Use a using namespace directive.
using namespace std:
......
cout << setw(6) << 1234 << endl;

// For long namespace name, you could define a shorthand (or alias) to the namespace
namespace shorthand = namespace-name;

Zusammenfassung

Die Schritte für die Datei-Eingabe/Ausgabe sind wie folgt:

  1. Erstellen Sie einen ifstream für die Eingabe oder einen ofstream für die Ausgabe.
  2. Verbinden Sie den Strom mit einer Eingabe- oder Ausgabedatei über open(filename).
  3. Führen Sie die formatierte Ausgabe über den Stream-Einfügungsooperator << oder die Eingabe über den Stream-Ausnahmeoperator >> durch, ähnlich wie cout << und cin >>.
  4. Schließen Sie die Datei und freien Sie den Strom.

In C++ gehört eine Entität (Variable, Funktion oder Klasse) zum globalen Namensraum (identifiziert durch :: ohne Namensraumname).