-
Notifications
You must be signed in to change notification settings - Fork 182
/
Copy pathlecture_12_cpp_io_and_functions.tex
1537 lines (1295 loc) · 46.2 KB
/
lecture_12_cpp_io_and_functions.tex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
\documentclass[12pt,letterpaper,twoside]{article}
\usepackage{../cme211}
\usepackage{algorithm2e}
\def\D{\mathrm{d}}
\usepackage{atbegshi}% http://ctan.org/pkg/atbegshi
\begin{document}
\title{Lecture 12: Functions and File IO in C++, \\ Preprocessor Step of Compilation\vspace{-5ex}}
\date{Fall 2020}
\maketitle
{\footnotesize
\paragraph{Topics:} Functions, Command line arguments and
formatting, (file) IO, pre-processor and \texttt{\#include}.
}
\vspace{-3ex}
\section{Functions in C++}
Functions allow us to decompose a program into smaller components
It is easier to implement, test, and debug portions of a program in isolation;
further, decomposition allows work to be spread among many people working mostly
independently. When done properly, resulting programs are easier to understand and
maintain: we seek to eliminate duplicated code and reuse functions across
multiple programs.
\href{https://en.wikipedia.org/wiki/Don%27t_repeat_yourself#DRY_vs_WET_solutions}
{Don't Repeat Yourself (DRY vs. WET code)}.
\begin{cpp}
int sum(int a, int b) {
int c = a + b;
return c;
}
\end{cpp}
Components:
{\footnotesize
\begin{verbatim}
return_type function_name(argument_type1 argument_var1, ...) {
// function body
return return_var; // return_var must have return_type
}
\end{verbatim}
}
Consider \texttt{src/sum1.cpp}:.
\begin{cpp}
#include <iostream>
int sum(int a, int b) {
int c = a + b;
return c;
}
int main() {
int a = 2, b = 3;
int c = sum(a,b);
std::cout << "c = " << c << std::endl;
}
\end{cpp}
We can compile with \texttt{g++ -Wall -Wextra -Wconversion sum1.cpp -o sum1} and run:
\begin{verbatim}
$ ./sum1
c = 5
\end{verbatim}
\subsection{Order of Declaration Matters}
Consider \texttt{src/sum2.cpp}: we attempt to \emph{use} a function \emph{before} defining it. This yields an error.
\begin{cpp}
#include <iostream>
int main() {
int a = 2, b = 3;
// the compiler does not yet know about sum()
int c = sum(a,b);
std::cout << "c = " << c << std::endl;
}
int sum(int a, int b) {
int c = a + b;
return c;
}
\end{cpp}
The compiler imports the objects defined in \texttt{iostream}, but when it gets
to the expression \texttt{sum(a,b)} it doesn't find an object named \texttt{sum} to be
defined in the current scope.
Output:
{\small
\begin{verbatim}
$ g++ -Wall -Wextra -Wconversion sum2.cpp -o sum2
sum2.cpp: In function 'int main()':
sum2.cpp:7:18: error: 'sum' was not declared in this scope
int c = sum(a,b); ^
\end{verbatim}
}
\paragraph{Function Declaration}
A \href{https://en.cppreference.com/w/cpp/language/function}{function \emph{declaration}}
specifies the function name, input
argument type(s), and output type only; it
need not specify the implementation (code) for the function, however it does
critically specify the information needed from a compiler in order to validate
its use within a program.
\paragraph{Function Definition}
A function \emph{definition} is the code that implements the function, and
it is legal to call a function if it has been defined or
\emph{simply declared}; see \texttt{src/sum3.cpp}.
\begin{cpp}
#include <iostream>
// Forward declaration or prototype
int sum(int a, int b);
int main() {
int a = 2, b = 3;
int c = sum(a,b);
std::cout << "c = " << c << std::endl;
}
// Function definition
int sum(int a, int b) {
int c = a + b;
return c;
}
\end{cpp}
{\small
\begin{verbatim}
$ g++ -Wall -Wextra -Wconversion sum3.cpp -o sum3
$ ./sum3
c = 5
\end{verbatim}
}
\subsection{Functions, Data Types, and Implicit Casting}
\subsubsection{Arguments (and Return Types) Cast to Match Function Declaration}
What happens if we provide arguments ``with incorrect type''? It really depends on what sub-routines the compiler finds (i.e. what we've defined and \texttt{\#include}d).\footnote{In CME 212, we'll emphasize a bit more details around
\href{https://en.cppreference.com/w/cpp/language/lookup}{lookup}, which may involve
\href{https://en.cppreference.com/w/cpp/language/adl}{inspecting arguments via argument dependent lookup} (and possibly template argument deduction) to disambiguate overloaded functions,
and how the compiler
determines which sub-routine to execute when a \href{https://en.cppreference.com/w/cpp/language/identifiers#Names}{\texttt{name}} is encountered.}
Consider \texttt{src/datatypes1.cpp}.
\begin{cpp}
#include <iostream>
int sum(int a, int b) {
return a + b;
}
int main() {
double a = 2.7, b = 3.8;
int c = sum(a,b); // Oops! Our sum() only expects integer args.
std::cout << "c = " << c << std::endl;
}
\end{cpp}
\paragraph{A sub-routine accepting numeric inputs is found, but implicit casting required}
Above, the compiler runs into \texttt{sum(a,b)} and sees that there is only a single
\texttt{sum()} function defined. This is good news, however the function happens to require
\texttt{int}eger arguments. We learned previously that although C++ is strongly typed,
some implicit casting can occur between numeric types.
With warning flags enabled, we are told that
variables \texttt{a} and \texttt{b} are implicitly being cast to \texttt{int} such that we can
proceed with evaluating \texttt{sum(a,b)}. Output:
{\small
\begin{verbatim}
$ g++ -Wall -Wextra -Wconversion datatypes1.cpp -o datatypes1
datatypes1.cpp: In function 'int main()':
datatypes1.cpp:14:18: warning: conversion to 'int' from 'double' may alter its value [-Wconversion]
int c = sum(a,b);
^
datatypes1.cpp:14:18: warning: conversion to 'int' from 'double' may alter its value [-Wconversion]
$ ./datatypes1
c = 5
\end{verbatim}
}
\paragraph{Return Value (Implicitly) Cast to Match Function Declaration}
Consider \texttt{src/datatypes2.cpp}:
\begin{cpp}
#include <iostream>
int sum(int a, int b) {
double c = a + b;
return c; // we are not returning the correct type
}
int main() {
int a = 2, b = 3;
int c = sum(a,b);
std::cout << "c = " << c << std::endl;
}
\end{cpp}
{\small
\begin{verbatim}
$ g++ -Wall -Wextra -Wconversion datatypes2.cpp -o datatypes2
datatypes2.cpp: In function 'int sum(int, int)':
datatypes2.cpp:6:10: warning: conversion to 'int' from 'double' may alter its value [-Wconversion]
return c;
^
$ ./datatypes2
c = 5
\end{verbatim}
}
\paragraph{Explicit Casting} Of course, we may explicitly instruct the compiler to obey
a cast command,
\texttt{src/datatypes3.cpp}.
\begin{cpp}
#include <iostream>
int sum(int a, int b) {
double c = a + b;
return (int)c;
}
int main() {
double a = 2.7, b = 3.8;
int c = sum((int)a,(int)b);
std::cout << "c = " << c << std::endl;
}
\end{cpp}
Output after compiling with \texttt{g++ -Wall -Wextra -Wconversion datatypes3.cpp -o datatypes3}:
{\small
\begin{verbatim}
$ ./datatypes3
c = 5
\end{verbatim}
}
\subsection{\texttt{void} Data Type: Absent/Unspecified}
We can think of using the \texttt{void} keyword to indicate absence of data, e.g.
\texttt{src/void1.cpp}.
\begin{cpp}
#include <iostream>
void printHeader(void) {
std::cout << "-------------------------" << std::endl;
std::cout << " MySolver v1.0 " << std::endl;
std::cout << "-------------------------" << std::endl;
}
int main() {
printHeader();
return 0;
}
\end{cpp}
Output:
{\small
\begin{verbatim}
$ g++ -Wall -Wextra -Wconversion void1.cpp -o void1
$ ./void1
-------------------------
MySolver v1.0
-------------------------
\end{verbatim}
}
\subsubsection{\texttt{void} Functions \emph{Cannot} Return Data} Attempting to return
a non-\texttt{void} (or absent) value from a \texttt{void} function results in a compiler
error; \texttt{src/void2.cpp}.
\begin{cpp}
#include <iostream>
void printHeader(void) {
std::cout << "-------------------------" << std::endl;
std::cout << " MySolver v1.0 " << std::endl;
std::cout << "-------------------------" << std::endl;
return 0;
}
int main() {
printHeader();
return 0;
}
\end{cpp}
Output:
\begin{verbatim}
$ g++ -Wall -Wextra -Wconversion void2.cpp -o void2
void2.cpp: In function 'void printHeader()':
void2.cpp:8:10: error: return-statement with a value, in function returning 'void' [-fpermissive]
return 0;
^
\end{verbatim}
\subsubsection{Explicitly Specifying a \texttt{void} Return} We can simply use \texttt{return;} to exit from a \texttt{void} returning function; e.g.
\texttt{src/void3.cpp}:
\begin{cpp}
#include <iostream>
void printHeader(void) {
std::cout << "-------------------------" << std::endl;
std::cout << " MySolver v1.0 " << std::endl;
std::cout << "-------------------------" << std::endl;
return;
}
int main() {
printHeader();
return 0;
}
\end{cpp}
Output after compiling with \texttt{g++ -Wall -Wextra -Wconversion void3.cpp -o void3}:
\begin{verbatim}
-------------------------
MySolver v1.0
-------------------------
\end{verbatim}
\subsubsection{Ignoring Return Value} This is simply done by not \emph{using} the return
value in an assignment or as part of an argument to a function call;
\texttt{src/ignore.cpp}:
\begin{cpp}
#include <iostream>
int sum(int a, int b) {
int c = a + b;
return c;
}
int main() {
int a = 2, b = 3;
sum(a,b); // legal to ignore return value if you want
}
\end{cpp}
Output:
\begin{verbatim}
$ g++ -Wall -Wextra -Wconversion ignore.cpp -o ignore
$ ./ignore
\end{verbatim}
\subsection{Function Scope} Functions have their own scope. When a function is called with
arguments, a new scope is created wherein the arguments are \emph{copied} into the new
environment. Variables outside the scope of the function are not typically accessible; see
\texttt{src/scope1.cpp}.
\begin{cpp}
#include <iostream>
int sum(void) {
int c = a + b; // Error: variables used which are not declared in scope.
return c;
}
int main() { /* All bets are off; program won't compile... */ }
\end{cpp}
Output:
\begin{verbatim}
$ g++ -Wall -Wextra -Wconversion scope1.cpp -o scope1
scope1.cpp: In function 'int sum()':
scope1.cpp:5:11: error: 'a' was not declared in this scope
int c = a + b;
^
scope1.cpp:5:15: error: 'b' was not declared in this scope
int c = a + b;
^
...
\end{verbatim}
\subsection{Global Scope} This is in general discouraged; you should rarely rely on this
practice, since if you intend for your program to be re-used by others then global variables can lead to conflicts and correctness bugs; see
\texttt{src/scope2.cpp}.
\begin{cpp}
#include <iostream>
// an be accessed from anywhere in the file (bad, bad, bad!)
int a;
void increment(void) { a++; }
int main() {
a = 2;
std::cout << "a = " << a << std::endl;
increment();
std::cout << "a = " << a << std::endl;
}
\end{cpp}
It's maybe not surprising that the program outputs \texttt{a = 2} followed by \texttt{a = 3}. However, the problem here really lies in the fact that variable \texttt{a} is being used within \texttt{main} and also this very same variable is always being used by our \texttt{increment} function; this is likely to lead to a subtle bug at best. Output:
{\small
\begin{verbatim}
$ g++ -Wall -Wextra -Wconversion scope2.cpp -o scope2
$ ./scope2
a = 2
a = 3
\end{verbatim}
}
\subsection{Passing Arguments (by \emph{value})}
We strive to be explicit about what the arguments our
functions depend on;
\texttt{src/passing1.cpp}.
\begin{cpp}
#include <iostream>
void increment(int a) {
a++;
std::cout << "a = " << a << std::endl;
}
int main() {
int a = 2;
increment(a);
std::cout << "a = " << a << std::endl;
}
\end{cpp}
Output:
{\small
\begin{verbatim}
$ g++ -Wall -Wextra -Wconversion passing1.cpp -o passing1
$ ./passing1
a = 3
a = 2
\end{verbatim}
}
\subsubsection{Passing Pointer Arguments (still by \emph{value})}
We must be careful of what is being copied! If we pass a pointer, the value gets
copied into a new pointer variable. The result is that ``both'' pointers reference the same
underlying data;
\texttt{src/passing2.cpp}.
\begin{cpp}
#include <iostream>
void increment(int a[2]) {
a[0]++;
a[1]++;
}
int main() {
int a[2] = {2, 3};
std::cout << "a[0] = " << a[0] << ", " << "a[1] = " << a[1] << std::endl;
increment(a);
std::cout << "a[0] = " << a[0] << ", " << "a[1] = " << a[1] << std::endl;
}
\end{cpp}
\begin{verbatim}
$ g++ -Wall -Wextra -Wconversion passing2.cpp -o passing2
$ ./passing2
a[0] = 2, a[1] = 3
a[0] = 3, a[1] = 4
\end{verbatim}
\paragraph{If we \emph{copy} a pointer, the value of the pointer refers to the same underlying data}
C++ defaults to pass by value, which means that when calling a
function the arguments are copied into a new stack-frame.
However, you need to be careful and recognize what is being copied!
In the case of a number like \texttt{int\ a}, what is being copied is
the value of the number,
but for a static array like \texttt{int\ a{[}2{]}},
what is being passed and copied is the location in memory where the
array data is stored.
\subsection{Functions and Modularity}
We strive to decompose our programs into reusable modules that are easily debugged and
inspected. This may mean splitting code across files; perhaps we have many complicated
sub-routines we must define in order to run a non-trivial \texttt{main} program; in such
an instance, it'd be preferable to compartmentalize our code; a simple example
\texttt{src/main4.cpp}.
\begin{cpp}
#include <iostream>
int sum(int a, int b);
int main() {
int a = 2, b = 3;
int c = sum(a,b);
}
\end{cpp}
\texttt{src/sum4.cpp}:
\begin{cpp}
int sum(int a, int b) {
int c = a + b;
return c;
}
\end{cpp}
Output:
{\small
\begin{verbatim}
$ g++ -Wall -Wextra -Wconversion main4.cpp sum4.cpp -o sum4
$ ./sum4
c = 5
\end{verbatim}
}
\subsubsection{Linker Errors} We'll discuss in a later lecture the details of the
compilation process. One step is to ensure that each function being used has a valid
definition. Suppose we have a prototype for a function, but no corresponding definition?
The compilation process will error during when trying to link dependencies from the main
routine; \texttt{src/main5.cpp}.
\begin{cpp}
#include <iostream>
int sum(int a, int b);
int main() {
int a = 2, b = 3;
int c = sum(a,b);
std::cout << "c = " << c << std::endl;
}
\end{cpp}
\texttt{src/sum5.cpp}:
\begin{cpp}
double sum(double a, double b) {
double c = a + b;
return c;
}
\end{cpp}
Output:
{\small
\begin{verbatim}
$ g++ -Wall -Wextra -Wconversion main5.cpp sum5.cpp -o sum5
/tmp/ccCKlsvX.o: In function main':
main5.cpp:(.text+0x21): undefined reference to sum(int, int)'
collect2: error: ld returned 1 exit status
\end{verbatim}
}
\section{Command line arguments}
Let's consider how we can pass arguments from the command line to a C++ program.
We've mentioned previously that
\href{https://en.cppreference.com/w/cpp/language/main_function}{\texttt{main()}}
specifies the start of a program, and
has a signature like
\begin{cpp}
int main(int argc, char *argv[]) { /* body */ }
\end{cpp}
where here
\begin{itemize} \item \texttt{argc} is a non-negative value representing the \emph{number} of arguments
passed to the program from the calling environment.
\item \texttt{argv} is a pointer to the first element of an \emph{array of pointers};
each element in the array is a sequence of
\href{https://en.cppreference.com/w/cpp/string/multibyte}
{null-terminated multibyte strings} (NTMBS)
representing arguments that were passed to the
program.\footnote{We are guaranteed that \texttt{argv[argc]} is a null pointer.} \end{itemize}
\begin{cpp}
#include <iostream>
int main(int argc, char *argv[]) {
// Display the command line arguments
for (int n = 0; n < argc; n++) {
std::cout << n << " " << argv[n] << std::endl;
}
return 0;
}
\end{cpp}
Output:
{\small
\begin{verbatim}
$ ./argv1 hello.txt 3.14 42
0 ./argv1
1 hello.txt
2 3.14
3 42
\end{verbatim}
}
\subsection{Formatting ({\small a Minimum Number of}) Command Line Arguments}
If our program requires a minimum number of inputs in order to execute, we must
reflect this in the control flow of the program. Notice that in the following example,
we simply print a helpful usage message to console and exit the program (without returning
an error).
\begin{cpp}
#include <iostream>
#include <string>
int main(int argc, char *argv[]) {
// Catch the case where insufficient arguments are provided.
// The first argument is the name of the executable being run!
if (argc < 4) {
std::cout << "Usage:" << std::endl;
std::cout << " " << argv[0] << " <filename> <param1> <param2>" << std::endl;
return 0;
}
// We're now guaranteed that three parameters were passed as argument to the program.
std::string filename = argv[1]; // Strings can be initialized with NTMBS.
double param1 = std::stof(argv[2]); // String-to-Float.
int param2 = std::stoi(argv[3]); // String-to-Integer.
std::cout << "filename = " << filename << std::endl;
std::cout << "param1 = " << param1 << std::endl;
std::cout << "param2 = " << param2 << std::endl;
}
\end{cpp}
Note that all the command line arguments are treated as \texttt{char*}s, whence we must
cast the underlying data to the appropriate type. We've taken advantage
of the fact that the compiler doesn't care about white-space to line up syntactically
similar statements to reflect their commonalities.
Output:
{\small
\begin{verbatim}
$ g++ -std=c++11 -Wall -Wconversion -Wextra argv2.cpp -o argv2
$ ./argv2 hello.txt 3.14 42
filename = hello.txt
param1 = 3.14
param2 = 42
\end{verbatim}
}
\vspace{-3ex}
\section{IO in C++}
\vspace{-2ex}
\subsection{Default IOStream Settings}
Without considering formatting options,
the \href{https://en.cppreference.com/w/cpp/io/basic_ios/init}{default iostream settings}
consider
\href{https://en.cppreference.com/w/cpp/io/ios_base/precision}{precision} when
formatting floating point values. The default settings
are to print up to six digits (including both integer and fractional digits), but to
omit trailing zeros if the result can be precisely displayed.
\begin{cpp}
#include <iostream>
int main() {
double a = 2.;
std::cout << "a = " << a << std::endl;
}
\end{cpp}
{\small
\begin{verbatim}
$ ./formatting1
a = 2
\end{verbatim}
}
Even though \texttt{a} is type \texttt{double}, it has no fractional part, so the
default formatting options encourage only the minimum number of digits to be
displayed accurately.
\subsection{Manipulators and Formatting Flags}
Just like Python, a significant amount of flexibility in string formatting is offered.
\vspace{-2ex}
\subsubsection{Manipulators}
\href{https://en.cppreference.com/w/cpp/io/manip}{Manipulators}
are helper functions that allow us to control
how input and output streams behave. E.g. displaying numeric values in
different \href{https://en.cppreference.com/w/cpp/io/manip/hex}{base-representations}
(decimal, octal, hexadecimal)
\href{https://en.cppreference.com/w/cpp/io/manip/left}{alignment}
(left or right), and
\href{https://en.cppreference.com/w/cpp/io/manip/uppercase}{case-sensitivity} (upper-case).
\begin{cpp}
#include <iostream>
int main() {
std::cout << "The decimal number 42 in decimal: " << std::dec << 42 << std::endl
<< "The decimal number 42 in octal: " << std::oct << 42 << std::endl
<< "The decimal number 42 in hex: " << std::hex << 42 << std::endl;
} \end{cpp}
Compiling and running, we see that
{\small
\begin{verbatim} g++ -std=c++11 formatting_flags.cpp -o formatting_flags
./formatting_flags
The decimal number 42 in decimal: 42
The decimal number 42 in octal: 52
The decimal number 42 in hex: 2a
\end{verbatim}
}
This should seem familiar, perhaps after we recall that in
\href{https://simple.wikipedia.org/wiki/Hexadecimal_numeral_system}{hex}
A-F maps to {\small \{10, $\ldots$, 15\}}.
\[
42 = {\bf 4} \times 10^1 + {\bf 2}\times 10^0 = {\bf 5}\times 8^1 + {\bf 2}\times 8^0 = {\bf 2}\times 16^1 + {\bf 10}\times 16^0.
\]
\subsubsection{Formatting Flags and \texttt{setf}}
We can apply manipulators as we did above, \emph{or}
we can use the \href{https://en.cppreference.com/w/cpp/io/ios_base/setf}{\texttt{setf}}
(and implicit Boolean operations) together with a \emph{formatting flag} (analogous to a manipulator)
to obtain a similar result.
Akin to each manipulator, there are \href{https://en.cppreference.com/w/cpp/io/ios_base/fmtflags}
{formatting flags in the standard library} which represent the \emph{state} of a stream's formatting options; they can be implemented as a
\href{https://en.cppreference.com/w/cpp/named_req/BitmaskType}{bitmask datatype}, and so
using \texttt{setf(flags)} can be thought of as effectively using
\href{https://en.cppreference.com/w/cpp/language/operator_arithmetic#Bitwise_logic_operators}{bitwise operations} to
set and clear relevant states.\footnote{Bitwise operators include unary negation (\texttt{\~}), binary infix \texttt{and} (\texttt{\&}), \texttt{or} (\texttt{|}), and
\texttt{XOR} (\texttt{\^}).} So, we could equivalently re-write our program above,
replacing manipulators (e.g. \texttt{std::dec})
with formatting flags (e.g. \texttt{std::ios\_base::dec}).
\begin{cpp}
#include <iostream>
#include <iomanip>
int main() {
std::cout.setf(std::ios_base::dec);
std::cout << "The number 42 in decimal: " << 42 << std::endl;
// Here, we set octal option, but first clear any formatting already specified.
std::cout.setf(std::ios_base::oct, std::ios_base::basefield);
std::cout << "The number 42 in octal: " << 42 << std::endl;
std::cout.setf(std::ios_base::hex, std::ios_base::basefield);
std::cout << "The number 42 in hex: " << 42 << std::endl;
} \end{cpp}
\paragraph{\texttt{setf} Updates Internal Flags (with Boolean Logic)}
Let \texttt{fl} denote the state of our internal formatting flags.
Then, the one-argument \texttt{setf} sub-routine simply applies the
bitmask with something like
\texttt{fl = fl | flags}, whereas the two-argument \texttt{setf}
sub-routine first clears bits specified by the mask (second argument)
and \emph{then} sets the (cleared) flags to those specified by first argument
with something like \newline
\texttt{fl = (fl \& \tilde mask) | (flags \& mask)}.
\subsection{Example Usage of Common Manipulators}
\subsubsection{Unconditionally Show Decimal Point via \texttt{showpoint}}
The \texttt{showpoint} manipulator specifies to unconditionally display fractional parts
of floats.
\begin{cpp}
#include <iostream>
int main() {
double a = 2., b = 3.14, c = 1.23456789, d = 12.3456789;
int e = 4;
std::cout.setf(std::ios::showpoint);
std::cout << "a = " << a << std::endl;
std::cout << "b = " << b << std::endl;
std::cout << "c = " << c << std::endl;
std::cout << "d = " << d << std::endl;
std::cout << "e = " << e << std::endl;
return 0;
}
\end{cpp}
Notice that in the following output, floating point representations always include six
digits (integer and fractional part included); since \texttt{int}s don't have a fractional
part, the \href{https://en.cppreference.com/w/cpp/io/manip/showpoint}{\texttt{showpoint}}
option doesn't apply.
\begin{verbatim}
$ ./formatting3
a = 2.00000
b = 3.14000
c = 1.23457
d = 12.3457
e = 4 \end{verbatim}
Notice that in the event that more than six digits of precision are required, that
the displayed value is rounded accordingly.
\subsubsection{Controlling Decimal Places}
We can get fixed-width formatting using
\href{https://en.cppreference.com/w/cpp/io/manip/fixed}{\texttt{fixed}}. The following
example always displays three decimal places for any floating point datatype, inclusive
of trailing zeros; see \texttt{formatting4.cpp}.
\begin{cpp}
#include <iostream>
int main() {
double a = 2., b = 3.14;
int c = 4;
//Always show 3 decimal places
std::cout.setf(std::ios_base::fixed, std::ios_base::floatfield);
std::cout.setf(std::ios_base::showpoint);
std::cout.precision(3);
std::cout << "a = " << a << std::endl;
std::cout << "b = " << b << std::endl;
std::cout << "c = " << c << std::endl; # Integers not affected by options re: fractional parts.
}
\end{cpp}
The above example uses formatting flags, but of course we could have used manipulators.
\subsubsection{Scientific Notation}
\begin{cpp}
int main() {
double a = 2., b = 3.14;
int c = 4;
std::cout.setf(std::ios::scientific, std::ios::floatfield);
std::cout.precision(3);
std::cout << "a = " << a << std::endl;
std::cout << "b = " << b << std::endl;
std::cout << "c = " << c << std::endl;
}
\end{cpp}
Output shows \texttt{a = 2.000e+00}, \texttt{b = 3.140e+00}, and \texttt{c = 4}.
\subsubsection{Field Width}
In the context of output, the
\href{https://en.cppreference.com/w/cpp/io/ios_base/width}{\texttt{std::ios\_base::width()}}
function manages the minimum number of characters to generate on output operations.
\begin{cpp}
#include <iostream>
int main() {
std::cout << "Minimum Field width...currently set to " << std::cout.width() << '\n';
std::cout << " 10 20 30\n";
std::cout << " ^ ^ ^\n";
std::cout << " | | |\n";
std::cout << "123456789-123456789-123456789|\n";
std::cout << 12.345 << std::endl;
std::cout.width(15);
std::cout << 12.345 << std::endl;
std::cout.width(30);
std::cout << 12.345 << std::endl;
}
\end{cpp}
{\small
\begin{verbatim}
$ ./formatting6
Minimum Field width...currently set to 0
10 20 30
^ ^ ^
| | |
123456789-123456789-123456789|
12.345
12.345
12.345
\end{verbatim}
}
\subsubsection{Fill character}
What if instead of a minimum output field width (via \texttt{std::ios\_base::width()}
as above), we wanted to specify an exact field width? For this, we can use
the manipulator \href{https://en.cppreference.com/w/cpp/io/manip/setw}
{\texttt{std::setw(int)}}.
\begin{cpp}
#include <iomanip>
#include <iostream>
int main() {
std::cout.fill('0');
for(int n = 0; n < 10; n++)
std::cout << std::setw(n < 5 ? 2 : n) << n << std::endl;
}
\end{cpp}
Recall the ternary operator (i.e. the
\href{https://en.cppreference.com/w/cpp/language/operator_other}{conditional operator}).
Output:
\begin{verbatim}
$ ./formatting7
00
...
04
00005
000006
0000007
00000008
000000009
\end{verbatim}
\subsection{File IO}
\begin{cpp}
#include <iostream>
#include <fstream>
int main() {
double a = 2., b = 3.14;
int c = 4;
std::ofstream f("formatting.txt");
f.setf(std::ios::showpoint);
f << "a = " << a << std::endl;
f << "b = " << b << std::endl;
f << "c = " << c << std::endl;
f.close();
}
\end{cpp}
Output:
\begin{verbatim}
$ ./formatting8
$ cat formatting.txt
a = 2.00000
b = 3.14000
c = 4
\end{verbatim}
\subsection{Examples of File IO in C++}
\subsubsection{Loading a Tabular Dataset - Homogeneous Data}
Remember the Movielens data? Each row contains exactly four integers separated each by
at least one space.
\begin{verbatim}
$ cat u.data
196 242 3 881250949
186 302 3 891717742
...
6 86 3 883603013
\end{verbatim}
\begin{cpp}
#include <fstream>
#include <iostream>
int main() {
std::ifstream f;
f.open("u.data");
if (f.is_open()) {
int uid, mid, rating, time;
while (f >> uid >> mid >> rating >> time) {
std::cout << "user = " << uid;
std::cout << ", movie = " << mid;
std::cout << ", rating = " << rating << std::endl;
}
f.close();
}
else {
std::cerr << "ERROR: Failed to open file" << std::endl;
}
return 0;
}
\end{cpp}
After compiling.
\begin{verbatim}
$ ./file1
user = 196, movie = 242, rating = 3
user = 186, movie = 302, rating = 3
...
user = 305, movie = 451, rating = 3
user = 6, movie = 86, rating = 3
\end{verbatim}
There are actually a \emph{lot} of non-trivial implementation details here.
\subsubsection{Revisiting \texttt{operator>>}}
See \texttt{src/file1.cpp}. Recall
how the stream insertion \texttt{operator>>}
behaves: it returns a reference to the remaining stream after reading a unit of data
from the stream. Basic signature:
\begin{cpp}
basic_istream& operator>>( int& value );
\end{cpp}
\paragraph{Return Type is a Reference to an Input Stream}
This signature tells us that the output type is a reference to (denoted by the trailing\texttt{\&} after the type) a \texttt{basic\_istream} object, and that the input argument
accepts an integer by reference (i.e. a variable we wish to mutate).
I.e. if we have an expression like \texttt{f >> uid}, then we can think of this as
calling the \texttt{operator>>} \emph{method} on our input-stream \emph{object}, with
\texttt{uid} provided as argument.
Whence \texttt{f >> uid >> mid >> rating >> time} first takes the
file-stream referred by
\texttt{f}, reads data into \texttt{uid} and returns the remaining stream.
We then repeat, this time reading the next datum and placing its contents into \texttt{mid}, etc.
There are two details I've glossed over: how do we know the number of white-spaces to skip,
and how do we determine how many characters to read from the input stream?
\paragraph{Formatted Input Functions and \texttt{std::ios\_base::skipws}}
You may be wondering what kind of logic is used in
parsing the white-spaces from our data, e.g. what happens if there is a varying number of
white-space characters between fields? The insertion stream operator
\href{https://en.cppreference.com/w/cpp/io/basic_istream/operator_gtgt}
{\texttt{std::operator$>\vspace{-1pt}>$}} is a \href{https://en.cppreference.com/w/cpp/named_req/FormattedInputFunction}{Formatted Input Function} adhering to several specifications -- one of which determines how to handle white-spaces i.e. the formatting flag
\texttt{ios\_base::skipws} for the input stream is inspected and if set to \texttt{true}
then (any arbitrary number of) white-spaces are skipped! The logic is to extract and