Download C++ I/O and Arithmetic Operations and more Exams C programming in PDF only on Docsity! 1. Cin and Cout: Streams ● C++ uses streams to perform input and output operations. ● A stream is an entity where a program can either insert or extract characters to/from. ● Streams are a source/destination of characters ● These characters are provided/accepted sequentially stream description cin standard input stream cout standard output stream Standard output (cout) ● Cout is used together with the insertion operator, <<. #include <iostream> using namespace std; int main() { cout << "Hello World! "; } ● The << operator inserts the data that follows it into the stream that precedes it. Multiple insertion operations (<<) may be chained in a single statement: Standard input (cin) ● Cin is used together with the extraction operator, which is written as >> ● The extraction operation on cin uses the type of the variable to determine how it interprets the characters read from the input. #include <iostream> using namespace std; int main() { float x,y; cout << "Please enter a value for x: "; cin >> x; cout << "Please enter a value for y: "; cin >> y; cout << "Values of x and y are:\n"; cout << "\tx = " << x << " \ty = " << y << '\n'; } 2. I/O Manipulators ● Setprecision: ○ Sets the decimal precision to be used to format floating-point values on output operations. ● Fixed: ○ Floating-point values are written using fixed-point notation ○ The value is represented with exactly as many digits in the decimal part as specified by the precision field ● Showpoint: ○ The decimal point is always written for floating point values inserted into the stream ○ Even for those whose decimal part is zero ● Scientific: ○ Floating-point values are written using scientific notation ○ The value is represented always with only one digit before the decimal point, ○ Decimal point is followed by as many decimal digits as the precision field #include <iostream> // std::cout, std::fixed #include <iomanip> // std::setprecision int main () { double f =3.14159; double d = 2; std::cout << std::setprecision(5) << f << '\n'; std::cout << std::setprecision(9) << f << '\n'; std::cout << std::setprecision(9) << d << '\n'; //std::cout << std::showpoint; std::cout << std::showpoint << std::setprecision(5) << f << '\n'; std::cout << std::showpoint << std::setprecision(9) << f << '\n'; std::cout << std::showpoint << std::setprecision(9) << d << '\n'; //std::cout << std::fixed; std::cout << std::fixed << std::setprecision(5) << f << '\n'; std::cout << std::fixed << std::setprecision(9) << f << '\n'; std::cout << std::fixed << std::setprecision(9) << d << '\n'; std::cout << std::scientific << f << '\n'; std::cout << std::scientific << f << '\n'; std::cout << std::scientific << d << '\n'; return 0; } Output: 3.1416 3.14159 2 3.1416 3.14159000