input and output - institut national de physique ...ipn · input and output (io) c/c++ io are based...
TRANSCRIPT
I. Hrivnacova @ Data Processing Course 2019 1
Input and Output
Data Processing Course,I. Hrivnacova, IPN Orsay
● Output to the Screen
● Input from the Keyboard
● IO Headers
● Output to a File
● Input from a File
● Formatting
I. Hrivnacova @ Data Processing Course 2019 2
C++ Program
● Including the necessary declarations for input and output ● Writing the string “Hello, World !” followed by std::endl symbol,
to the standard output
/* The first C++ program * - just outputs 'Hello, World !' */
#include <iostream>
using namespace std;
int main() { // print “Hello, World !” on the screen cout << “Hello, World !” << endl; }
I. Hrivnacova @ Data Processing Course 2019 3
Input and Output (IO)
● C/C++ IO are based on streams,which are sequence of bytesflowing in and out of the programs(just like water and oil flowingthrough a pipe).– In input operations, data bytes flow
from an input source (such askeyboard, file, network or anotherprogram) into the program.
– In output operations, data bytesflow from the program to an outputsink (such as console, file, networkor another program).
Chua Hock-Chuan: Programming Notes
I. Hrivnacova @ Data Processing Course 2019 4
Input and Output
● The input/output (I/O) functionality isprovided in components of standardlibrary:– #include <iostream>
● Standard channels to provideinput/output:– Generally assigned to the keyboard
(input) and the screen (output)
– Can be redirected by the operatingsystem to a file
● The standard library defines types andobjects specially designed for IO
● Objects:– cin, cout - input channel (the
keyboard), output channel (the screen)
– Global stream objects, they are alreadydeclared, and so available for use
● Types:– istream, ostream : defines the type for
objects that can be used for input, output
● Operators:– <<, >> operator: Send, receive data
t/fromo the output/an input channel
I. Hrivnacova @ Data Processing Course 2019 5
Output to the Screen
● We use the stream std::cout and the operator <<
#include <iostream>#include <string>
using namespace std;
int main (){ int i = 1; float f = 2.3; string s = "abcd"; cout << " i=" << i << " f=" << f << " s=" << s << std::endl;}
The operator << is intelligent: itadapts to the type of the object to itsright
I. Hrivnacova @ Data Processing Course 2019 6
Output to the Screen
● We use the stream std::cout and the operator <<
#include <iostream>#include <string>
using namespace std;
int main (){ int i = 1; float f = 2.3; string s = "abcd"; cout << " i=" << i << " f=" << f << " s=" << s << std::endl;}
Program output:
> ./testOutput
i=1 f=2.3 s=abcd
I. Hrivnacova @ Data Processing Course 2019 7
Input from the Keyboard
● We use the stream std::cin and the operator >>#include <iostream>#include <string>
using namespace std;
int main (){ int i; float f; string s; cin >> i >> f >> s;
cout << " i=" << i << " f=" << f << " s=" << s << endl;}
The entries in cascade can beseparated by any separationcharacter: space, TAB, CR
I. Hrivnacova @ Data Processing Course 2019 8
Input from the Keyboard
● We use the stream std::cin and the operator >>#include <iostream>#include <string>
using namespace std;
int main (){ int i; float f; string s; cin >> i >> f >> s;
cout << " i=" << i << " f=" << f << " s=" << s << endl;}
Program output:
> ./testInput
1
2
Blablah
i=1 f=2 s=Blablah
I. Hrivnacova @ Data Processing Course 2019 9
Input from the Keyboard (2)
● We use the stream std::cin and the function std::getline()
#include <iostream>#include <string>
using namespace std;
int main (){ string line; getline(cin, line); cout << "Read: " << line << endl;
getline(cin, line); cout << "Read: " << line << endl; // ... }
● We read the entire line, even ifit contains separators (space,tab) until the character CR.
● We must analyse the linesourselves
I. Hrivnacova @ Data Processing Course 2019 10
Input from the Keyboard (2)
● We use the stream std::cin and the function std::getline()
#include <iostream>#include <string>
using namespace std;
int main (){ string line; getline(cin, line); cout << "Read: " << line << endl;
getline(cin, line); cout << "Read: " << line << endl; // ... }
Program output:
> ./testInput2
A text
Read: A text
Another text
Read: Another text
I. Hrivnacova @ Data Processing Course 2019 11
IO Header Files
Header File Function and Description<iostream> This file defines the cin, cout, cerr and clog objects,
which correspond to the standard input stream, thestandard output stream, the un-buffered and bufferedstandard error stream, respectively.
<fstream> This file declares services for user-controlled fileprocessing.
<iomanip> This file declares services useful for performing formattedI/O with so-called parameterized stream manipulators, suchas setw and setprecision.
I. Hrivnacova @ Data Processing Course 2019 12
Files
● The file input/output (I/O) functionalityis provided in components ofstandard library:– #include <fstream>
● Types:– ifstream, ofstream : define the
types for objects that can be used forinput, output
– They are of the same family as istream and ostream, and so theobjects of this type can be manipulatedthe same way
● Using operators: <<,>>
● Objects– There are no global file
stream objects (such as cin and cout), we have to definethem ourselves before we canuse them
– We choose the names of ourstream objects
ifstream inFile;ofstream outFile;
I. Hrivnacova @ Data Processing Course 2019 13
Open/Close a File
● The name of theinput/output filecan be definedeither at creatingthe file or at fileopenning
// create (open) a file a data file // “file.txt”ofstream outFile("file.txt");// do somethingoutFile.close();
// create a file streamofstream outFile;// create (open) a data file “file.txt”outFile.open("file.txt");// do somethingoutFile.close();
I. Hrivnacova @ Data Processing Course 2019 14
Output to a File#include <fstream>#include <iostream>#include <string>
using namespace std;
ofstream outFile;
int main (){ int i = 1; float f = 2.3; string s = "abcd";
outFile.open("file.txt"); if ( ! outFile.is_open() ) { cerr << "Cannot open file" << endl; return 1; }
outFile << i << " " << f << " " << s << std::endl;
outFile.close();}
● The operation to open afile may fail– If the output file does not
exist, if one has no rightto write to the directoryfor the output file ...
– We have to test the resultof the open operation:
● The operator << is usedin the same way as tooutput to the screen
I. Hrivnacova @ Data Processing Course 2019 15
Output to a File
Program output:
> ./testFileOutput
> more file.txt
1 2.3 abcd
#include <fstream>#include <iostream>#include <string>
using namespace std;
ofstream outFile;
int main (){ int i = 1; float f = 2.3; string s = "abcd";
outFile.open("file.txt"); if ( ! outFile.is_open() ) { cerr << "Cannot open file" << endl; return 1; }
outFile << i << " " << f << " " << s << std::endl;
outFile.close();}
I. Hrivnacova @ Data Processing Course 2019 16
Input from a File
● The operation to open afile may fail– The input file may not
exist
– We have to test the resultof the open operation:
● The operator >> is usedin the same way as toinput from the keyboard
#include <fstream>#include <iostream>#include <string>
using namespace srd;
ifstream inFile;
int main (){ int i; float f; std::string s;
inFile.open("file.txt"); if ( ! inFile.is_open() ) { cerr << "Cannot open file" << endl; return 1; }
inFile >> i >> f >> s;
std::cout << " i=" << i << " f=" << f << " s=" << s << std::endl;}
I. Hrivnacova @ Data Processing Course 2019 17
Input from a File
Program output:
> ./testFileInput
i=1 f=2.3 s=abcd
#include <fstream>#include <iostream>#include <string>
using namespace srd;
ifstream inFile;
int main (){ int i; float f; std::string s;
inFile.open("file.txt"); if ( ! inFile.is_open() ) { cerr << "Cannot open file" << endl; return 1; }
inFile >> i >> f >> s;
std::cout << " i=" << i << " f=" << f << " s=" << s << std::endl;}
I. Hrivnacova @ Data Processing Course 2019 18
Formatting Output
● The <iomanip> header provides so-called I/Omanipulators for formatting output (and input):
setw(int field-width) Set the field width for the next IO operation. setw() is non-sticky and must be issued prior to each IOoperation.
setfill(char fill-char) Set the filled character for padding to the field width.left|right|internal: set the alignment.
left|right|internal Set the alignment.
fixed|scientific Use fixed-point notation (e.g, 12.34) or scientific notation(e.g., 1.23e+006). For floating-point numbers.
setprecision(intnumDecimalDigits)
Specify the number of digits after the decimal point. Forfloating-point numbers.
boolalpha|noboolalpha display bool values as alphabetic string (true/false) or 1/0. Forbool.
I. Hrivnacova @ Data Processing Course 2019 19
Formatting Output#include <iostream>#include <iomanip> // Needed to do formatted I/Ousing 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;}
I. Hrivnacova @ Data Processing Course 2019 20
Formatting Output#include <iostream>#include <iomanip> // Needed to do formatted I/Ousing 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;}
Program output:> ./testFormatting3.1416| 3.1416| 3.1416||--3.1416|----3.1416|3.1416e+000false