Learning Cplusplus
From w3cyberlearnings
Contents |
Lecture 1 C++ Input/Output
- Two points of view to a program:
Output Data = Program(Input Data) Program = Model of a problem domain Execution = Simulation of the problem domain
Example
#include <iostream> using namespace std; int main() { int id; float av; cout << "Enter the id and the average: "; cin >> id >> av; cout << "Id " << id << '\n‘; cout << "Average " << av << '\n'; return 0; }
Using cin and cout
- cin, cout and cerr are variables, defined in iostream;
- cin refers to the standard input stream; cout refers to the standard output stream; and cerr refers to the standard error (output) stream;
- The default action of the input operator >> is to skip white space before reading the next input item (even in the case of char);
- The operators << and >> associate from the left;
- The value of the expression cin >> id refers to the same input stream, after the vallue assigned to id is removed from the stream.
Example 2
Where a true or false value is expected, an expression such as cin >> val is converted to true, if a value is read into val, and false otherwise
#include <iostream> using namespace std; int main() { int val, sum = 0; cout << "Enter next number: "; while ( cin >> val ) { sum += val; cout << "Enter next number: "; } cout << "Sum of all values: "<<sum<<'\n'; return 0; }
Manipulators
- Used to manipulate the output, #include <iomanip> required.
- Except for setw, a manipulator permanently changes the state of the stream to which it is applied.
- setw sets the width of the output field.
- setfill is used to specify a particular fill character, used to fill the extra space when the field width is greater than the item to be output.
- setprecision is used to specify the number of digits of precision of floating-point numbers.
Example
cout << setprecision(5) << 12.48381344; // Result 12.484
Example 3
#include <iostream> #include <iomanip> using namespace std; int main() { float a = 1.05, b = 10.15, c = 200.87; cout << setfill( '*' ); cout << setw( 10 ) << a << '\n'; cout << setw( 10 ) << b << '\n'; cout << setw( 10 ) << c << '\n'; return 0; }
Out put
Output ******1.05 *****10.15 ****200.87
Input from and output to disk-file
ifstream infile |
ofstream outfile |
ifstream infile; infile.open(“Asd.dat”); infile >> myvariable; infile.close(); |
ofstream outfile; outfile.open(“Qwe.xyz”); outfile << “hello” << 5; outfile.close(); |