C++ Formatting, File IO and Namespace

C++C++Beginner
Practice Now

Introduction

In this lab, you will learn the formatting, file I/O, and namespace in C++. You will learn how to format output, how to format input, how to read and write files, and how to use namespaces.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL cpp(("`C++`")) -.-> cpp/IOandFileHandlingGroup(["`I/O and File Handling`"]) cpp(("`C++`")) -.-> cpp/SyntaxandStyleGroup(["`Syntax and Style`"]) cpp(("`C++`")) -.-> cpp/BasicsGroup(["`Basics`"]) cpp(("`C++`")) -.-> cpp/ControlFlowGroup(["`Control Flow`"]) cpp(("`C++`")) -.-> cpp/FunctionsGroup(["`Functions`"]) cpp(("`C++`")) -.-> cpp/OOPGroup(["`OOP`"]) cpp/IOandFileHandlingGroup -.-> cpp/output("`Output`") cpp/SyntaxandStyleGroup -.-> cpp/comments("`Comments`") cpp/BasicsGroup -.-> cpp/variables("`Variables`") cpp/BasicsGroup -.-> cpp/data_types("`Data Types`") cpp/BasicsGroup -.-> cpp/operators("`Operators`") cpp/BasicsGroup -.-> cpp/strings("`Strings`") cpp/BasicsGroup -.-> cpp/booleans("`Booleans`") cpp/ControlFlowGroup -.-> cpp/conditions("`Conditions`") cpp/ControlFlowGroup -.-> cpp/while_loop("`While Loop`") cpp/FunctionsGroup -.-> cpp/function_parameters("`Function Parameters`") cpp/OOPGroup -.-> cpp/classes_objects("`Classes/Objects`") subgraph Lab Skills cpp/output -.-> lab-178541{{"`C++ Formatting, File IO and Namespace`"}} cpp/comments -.-> lab-178541{{"`C++ Formatting, File IO and Namespace`"}} cpp/variables -.-> lab-178541{{"`C++ Formatting, File IO and Namespace`"}} cpp/data_types -.-> lab-178541{{"`C++ Formatting, File IO and Namespace`"}} cpp/operators -.-> lab-178541{{"`C++ Formatting, File IO and Namespace`"}} cpp/strings -.-> lab-178541{{"`C++ Formatting, File IO and Namespace`"}} cpp/booleans -.-> lab-178541{{"`C++ Formatting, File IO and Namespace`"}} cpp/conditions -.-> lab-178541{{"`C++ Formatting, File IO and Namespace`"}} cpp/while_loop -.-> lab-178541{{"`C++ Formatting, File IO and Namespace`"}} cpp/function_parameters -.-> lab-178541{{"`C++ Formatting, File IO and Namespace`"}} cpp/classes_objects -.-> lab-178541{{"`C++ Formatting, File IO and Namespace`"}} end

Content Preview

Use <iomanip> I/O manipulators for formatting input and output.

The <fstream> header provides ifstream (input file stream) and ofstream (output file stream) for file input and output.

  • Formatting input and output
  • File input and output
  • Namespace

Formatting Input/Output using IO Manipulators (Header )

The <iomanip> header provides so-called I/O manipulators for formatting input and output:

  • setw(int field-widht): set the field width for the next IO operation. setw() is non-sticky and must be issued prior to each IO operation. The field width is reset to the default after each operation (with just enough width to accommodate the field).
  • setfill(char fill-char): set the filled character for padding to the field width.
  • left|right|internal: set the alignment
  • fixed/scientific (for floating-point numbers): use fixed-point notation (e.g, 12.34) or scientific notation (e.g., 1.23e+006).
  • setprecision(int numDecimalDigits) (for floating-point numbers): specify the number of digits after the decimal point.
  • boolalpha/noboolalpha (for bool): display bool values as alphabetic string (true/false) or 1/0.
/* 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;
}

Output:

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;
}

Output:

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

File Input/Output

To test the file input and output, firstly create a file called in.txt and write some int numbers in it seperated by space. After execution, the result of calculation will be write into a file out.txt .

/* 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;
}

Output:

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

Program Notes:

  • Once the file is opened, you can use >> and << for input and output, similar to cin >> and cout <<. (Advanced note: ifstream is a subclass of istream, where cin belongs. ofstream is a subclass of ostream, where cout belongs.)
  • Similarly, IO manipulators, such as fixed, setprecision() and setw(), work on the file streams.

Namespace

When you use different library modules, there is always a potential for name crashes, as different library may use the same name for different purposes. This problem can be resolved via the use of namespace in C++. A namespace is a collection for identifiers under the same naming scope. (It is known as package in UML and Java.) The entity name under a namespace is qualified by the namespace name, followed by :: (known as scope resolution operator), in the form of namespace::entityName.

To place an entity under a namespace, use keyword namespace as follow:

// 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

A namespace can contain variables, functions, arrays, and compound types such as classes and structures.

#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
}

Output:

8
9
image desc

Using Namespace

// 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;

Summary

The steps for file input/output are:

  1. Create a ifstream for input, or ofstream for output.
  2. Connect the stream to an input or output file via open(filename).
  3. Perform formatted output via stream insertion operator <<, or input via stream extraction operator >>, similar to cout << and cin >>.
  4. Close the file and free the stream.

In C++, an entity (variable, function, or class) belongs to the global namespace (identified by :: with no namespace name).

Other C++ Tutorials you may like