some changes to chapter 6

This commit is contained in:
davoudn 2024-04-08 23:45:18 -07:00
parent 89f2f8faa5
commit 754b4098da
1139 changed files with 266245 additions and 0 deletions

View File

@ -0,0 +1,10 @@
# C++20 for Programmers
This repository contains the source code and supporting files associated with our book **C++20 for Programmers**. https://deitel.com/c-plus-plus-20-for-programmers
These files are Copyright 2022 by Deitel & Associates, Inc. and Pearson Education, Inc. All Rights Reserved.
You may use these files for your personal purposes, but please do not repost them without our express written consent.
If you have any questions, open an issue in the Issues tab or email us: deitel at deitel dot com.
The authors and publisher of this book have used their best efforts in preparing this book. These efforts include the development, research, and testing of the theories and programs to determine their effectiveness. The authors and publisher make no warranty of any kind, expressed or implied, with regard to these programs or to the documentation contained in this book. The authors and publisher shall not be liable in any event for incidental or consequential damages in connection with, or arising out of, the furnishing, performance, or use of these programs.

View File

@ -0,0 +1,79 @@
// Randomly generate numbers between 1 and 1000 for user to guess.
#include <iostream>
#include <random> // contains C++11 random number generation features
using namespace std;
bool isCorrect(int, int); // function prototype
int main() {
// use the default random-number generation engine to
// produce uniformly distributed pseudorandom int values from 1 to 1000
default_random_engine engine{random_device{}()};
uniform_int_distribution<int> randomInt{1, 1000};
char response = 'n'; // determines whether to continue playing
// loop until user types 'n' to quit game
do {
// generate random number between 1 and 1000
// 1 is shift, 1000 is scaling factor
const int answer{randomInt(engine)};
// prompt for guess
cout << "I have a number between 1 and 1000.\n"
<< "Can you guess my number?\n"
<< "Please type your first guess." << endl << "? ";
int guess;
cin >> guess;
// loop until correct number
while (!isCorrect(guess, answer)) {
cin >> guess;
}
// prompt for another game
cout << "\nExcellent! You guessed the number!\n"
<< "Would you like to play again (y or n)? ";
cin >> response;
cout << endl;
} while (response == 'y');
return 0; // indicate successful termination
}
// isCorrect returns true if guess equals answer;
// otherwise it displays a hint and returns false
bool isCorrect(int guess, int answer) {
// guess is correct
if (guess == answer) {
return true;
}
// guess is incorrect; display hint
if (guess < answer) {
cout << "Too low. Try again.\n? ";
}
else {
cout << "Too high. Try again.\n? ";
}
return false;
} // end function isCorrect
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/

View File

@ -0,0 +1,29 @@
// fig02_01.cpp
// Text-printing program.
#include <iostream> // enables program to output data to the screen
// function main begins program execution
int main() {
std::cout << "Welcome to C++!\n"; // display message
return 0; // indicate that program ended successfully
} // end function main
/*************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/

View File

@ -0,0 +1,26 @@
// fig02_02.cpp
// Displaying a line of text with multiple statements.
#include <iostream> // enables program to output data to the screen
// function main begins program execution
int main() {
std::cout << "Welcome ";
std::cout << "to C++!\n";
} // end function main
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/

View File

@ -0,0 +1,25 @@
// fig02_03.cpp
// Displayings multiple lines of text with a single statement.
#include <iostream> // enables program to output data to the screen
// function main begins program execution
int main() {
std::cout << "Welcome\nto\n\nC++!\n";
} // end function main
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/

View File

@ -0,0 +1,38 @@
// fig02_04.cpp
// Addition program that displays the sum of two integers.
#include <iostream> // enables program to perform input and output
// function main begins program execution
int main() {
// declaring and initializing variables
int number1{0}; // first integer to add (initialized to 0)
int number2{0}; // second integer to add (initialized to 0)
int sum{0}; // sum of number1 and number2 (initialized to 0)
std::cout << "Enter first integer: "; // prompt user for data
std::cin >> number1; // read first integer from user into number1
std::cout << "Enter second integer: "; // prompt user for data
std::cin >> number2; // read second integer from user into number2
sum = number1 + number2; // add the numbers; store result in sum
std::cout << "Sum is " << sum << "\n"; // display sum
} // end function main
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/

View File

@ -0,0 +1,56 @@
// fig02_05.cpp
// Comparing integers using if statements, relational operators
// and equality operators.
#include <iostream> // enables program to perform input and output
using std::cout; // program uses cout
using std::cin; // program uses cin
// function main begins program execution
int main() {
int number1{0}; // first integer to compare (initialized to 0)
int number2{0}; // second integer to compare (initialized to 0)
cout << "Enter two integers to compare: "; // prompt user for data
cin >> number1 >> number2; // read two integers from user
if (number1 == number2) {
cout << number1 << " == " << number2 << "\n";
}
if (number1 != number2) {
cout << number1 << " != " << number2 << "\n";
}
if (number1 < number2) {
cout << number1 << " < " << number2 << "\n";
}
if (number1 > number2) {
cout << number1 << " > " << number2 << "\n";
}
if (number1 <= number2) {
cout << number1 << " <= " << number2 << "\n";
}
if (number1 >= number2) {
cout << number1 << " >= " << number2 << "\n";
}
} // end function main
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/

View File

@ -0,0 +1,52 @@
// fig02_06.cpp
// Standard library string class test program.
#include <iostream>
#include <string>
using namespace std;
int main() {
string s1{"happy"};
string s2{" birthday"};
string s3; // creates an empty string
// display the strings and show their lengths (length is C++20)
cout << "s1: \"" << s1 << "\"; length: " << s1.length()
<< "\ns2: \"" << s2 << "\"; length: " << s2.length()
<< "\ns3: \"" << s3 << "\"; length: " << s3.length();
// compare strings with == and !=
cout << "\n\nThe results of comparing s2 and s1:" << boolalpha
<< "\ns2 == s1: " << (s2 == s1)
<< "\ns2 != s1: " << (s2 != s1);
// test string member function empty
cout << "\n\nTesting s3.empty():\n";
if (s3.empty()) {
cout << "s3 is empty; assigning to s3;\n";
s3 = s1 + s2; // assign s3 the result of concatenating s1 and s2
cout << "s3: \"" << s3 << "\"";
}
// testing new C++20 string member functions
cout << "\n\ns1 starts with \"ha\": " << s1.starts_with("ha") << "\n";
cout << "s2 starts with \"ha\": " << s2.starts_with("ha") << "\n";
cout << "s1 ends with \"ay\": " << s1.ends_with("ay") << "\n";
cout << "s2 ends with \"ay\": " << s2.ends_with("ay") << "\n";
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/

View File

@ -0,0 +1,41 @@
// fig03_01.cpp
// Solving the class-average problem using counter-controlled iteration.
#include <iostream>
using namespace std;
int main() {
// initialization phase
int total{0}; // initialize sum of grades entered by the user
int gradeCounter{1}; // initialize grade # to be entered next
// processing phase uses counter-controlled iteration
while (gradeCounter <= 10) { // loop 10 times
cout << "Enter grade: "; // prompt
int grade;
cin >> grade; // input next grade
total = total + grade; // add grade to total
gradeCounter = gradeCounter + 1; // increment counter by 1
}
// termination phase
int average{total / 10}; // int division yields int result
// display total and average of grades
cout << "\nTotal of all 10 grades is " << total;
cout << "\nClass average is " << average << "\n";
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
*************************************************************************/

View File

@ -0,0 +1,58 @@
// fig03_02.cpp
// Solving the class-average problem using sentinel-controlled iteration.
#include <iostream>
#include <iomanip> // parameterized stream manipulators
using namespace std;
int main() {
// initialization phase
int total{0}; // initialize sum of grades
int gradeCounter{0}; // initialize # of grades entered so far
// processing phase
// prompt for input and read grade from user
cout << "Enter grade or -1 to quit: ";
int grade;
cin >> grade;
// loop until sentinel value is read from user
while (grade != -1) {
total = total + grade; // add grade to total
gradeCounter = gradeCounter + 1; // increment counter
// prompt for input and read next grade from user
cout << "Enter grade or -1 to quit: ";
cin >> grade;
}
// termination phase
// if user entered at least one grade
if (gradeCounter != 0) {
// use number with decimal point to calculate average of grades
double average{static_cast<double>(total) / gradeCounter};
// display total and average (with two digits of precision)
cout << "\nTotal of the " << gradeCounter
<< " grades entered is " << total;
cout << setprecision(2) << fixed;
cout << "\nClass average is " << average << "\n";
}
else { // no grades were entered, so output appropriate message
cout << "No grades were entered\n";
}
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
*************************************************************************/

View File

@ -0,0 +1,53 @@
// fig03_03.cpp
// Analysis of examination results using nested control statements.
#include <iostream>
using namespace std;
int main() {
// initializing variables in declarations
int passes{0};
int failures{0};
int studentCounter{1};
// process 10 students using counter-controlled loop
while (studentCounter <= 10) {
// prompt user for input and obtain value from user
cout << "Enter result (1 = pass, 2 = fail): ";
int result;
cin >> result;
// if...else is nested in the while statement
if (result == 1) {
passes = passes + 1;
}
else {
failures = failures + 1;
}
// increment studentCounter so loop eventually terminates
studentCounter = studentCounter + 1;
}
// termination phase; prepare and display results
cout << "Passed: " << passes << "\nFailed: " << failures << "\n";
// determine whether more than 8 students passed
if (passes > 8) {
cout << "Bonus to instructor!\n";
}
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
*************************************************************************/

View File

@ -0,0 +1,36 @@
// fig03_04.cpp
// Prefix increment and postfix increment operators.
#include <iostream>
using namespace std;
int main() {
// demonstrate postfix increment operator
int c{5};
cout << "c before postincrement: " << c << "\n"; // prints 5
cout << " postincrementing c: " << c++ << "\n"; // prints 5
cout << " c after postincrement: " << c << "\n"; // prints 6
cout << endl; // skip a line
// demonstrate prefix increment operator
c = 5;
cout << " c before preincrement: " << c << "\n"; // prints 5
cout << " preincrementing c: " << ++c << "\n"; // prints 6
cout << " c after preincrement: " << c << "\n"; // prints 6
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
*************************************************************************/

View File

@ -0,0 +1,44 @@
# CMakeLists.txt
# Mark Guerra
# 11/1/2015
cmake_minimum_required(VERSION 2.8)
project(BigNumber)
set(BigNumber_VERSION_MAJOR 1)
set(BigNumber_VERSION_MINOR 0)
if (WIN32)
set(c++version -std=gnu++14)
else()
set(c++version -std=c++14)
endif()
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -Weffc++ -pedantic -Wno-unused-function ${c++version}")
set(CMAKE_BUILD_TYPE Release)
set(SOURCE_FILES
src/bignumber.cpp main.cpp )
add_library(BigNumber ${SOURCE_FILES})
set(CMAKE_BUILD_TYPE Debug)
if(WIN32)
install(TARGETS BigNumber DESTINATION C:/Libs/BigNumber/lib)
install(FILES src/bignumber.h DESTINATION C:/Libs/BigNumber/include)
else()
install(TARGETS BigNumber DESTINATION ~/Library/Frameworks/BigNumber/lib)
install(FILES src/bignumber.h DESTINATION ~/Library/Frameworks/BigNumber/include)
endif()
install(TARGETS BigNumber DESTINATION ${CMAKE_CURRENT_LIST_DIR}/bin/BigNumber/lib)
install(FILES src/bignumber.h DESTINATION ${CMAKE_CURRENT_LIST_DIR}/bin/BigNumber/include)
add_custom_command(
TARGET BigNumber
POST_BUILD
COMMAND ${CMAKE_COMMAND} --build ${CMAKE_BINARY_DIR} --target install
)
add_executable(BigNumberRun ${SOURCE_FILES})

View File

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2016-2017 Mark Guerra
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@ -0,0 +1,223 @@
# BigNumber
![BigNumber build](https://travis-ci.org/Limeoats/BigNumber.svg?branch=master)
[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://github.com/Limeoats/BigNumber/blob/master/LICENSE.md)
BigNumber is a C++ class that allows for the creation and computation of arbitrary-length
integers.
The maximum possible length of a BigNumber is `std::string::max_size`.
## Installation
To add BigNumber to your C++ project, you can download the `bin` folder from this repository, which
contains the library and include files.
Then, simply include the header file in whichever file you need a BigNumber and link to the library file.
`#include "bignumber.h"`
## Usage
### `BigNumber(string)`
You can also use the `=` operator to set a BigNumber equal to an existing BigNumber, a number, or
a string of numbers.
Examples:
BigNumber b("5"); //BigNumber b is created with value 5.
BigNumber c("-20"); //BigNumber c is created with value -20.
BigNumber d("0"); //BigNumber d is created with value 0.
BigNumber e = b; //BigNumber e is created with value 5.
BigNumber f = 30; //BigNumber f is created with value 30.
BigNumber g = "2060"; //BigNumber g is created with value 2060.
BigNumber h(22); //BigNumber h is created with value 22.
## Methods
### `add(BigNumber other)`
Adds another BigNumber to the current instance
`BigNumber("4").add(BigNumber("20")) => BigNumber("24")`
### `subtract(BigNumber other)`
Subtracts another BigNumber from the current instance
`BigNumber("30").subtract(BigNumber("45")) => BigNumber("-15")`
### `multiply(BigNumber other)`
Multiplies the BigNumber by another BigNumber
`BigNumber("12").multiply(BigNumber("4")) => BigNumber("48")`
### `divide(BigNumber other)`
Divides the BigNumber by another BigNumber
`BigNumber("30").divide(BigNumber("5")) => BigNumber("6")`
### `pow(int exponent)`
Raises the BigNumber to the power of the exponent
`BigNumber("2").pow(3) => BigNumber("8")`
### `getString()`
Returns the BigNumber as an std::string
`BigNumber("3824").getString() => "3824"`
### `setString(std::string newStr)`
Sets the BigNumber's internal number string to a new string
`BigNumber("2847").setString("38") => BigNumber("38")`
### `negate()`
Changes the sign of the BigNumber
BigNumber("3").negate() => BigNumber("-3")
BigNumber("-27").negate() => BigNumber("27")
### `equals(BigNumber other)`
Checks if the other BigNumber is equal to this one
`BigNumber("24").equals(BigNumber("28")) => false`
### `digits()`
Returns the number of digits in the BigNumber
`BigNumber("28374").digits() => 5`
### `isNegative()`
Determines whether a BigNumber is negative
`BigNumber("-278").isNegative() => true`
### `isPositive()`
Determines whether a BigNumber is positive
`BigNumber("-3").isPositive() => false`
### `isEven()`
Determines whether a BigNumber is even
`BigNumber("28472310").isEven() => true`
### `isOdd()`
Determines whether a BigNumber is odd
`BigNumber("283427").isOdd() => true`
### `abs()`
Gets the absolute value of the BigNumber
`BigNumber("-26").abs() => BigNumber("26")`
## Operator overloads
The following operators have been overloaded to work with BigNumbers:
### `<<`
Output stream operator
`std::cout << BigNumber("26") << std::endl => 26`
### `+`
Addition operator
`BigNumber("2") + BigNumber("4") => BigNumber("6")`
### `-`
Subtraction operator
`BigNumber("0") - BigNumber("2000") => BigNumber("-2000")`
### `*`
Multiplication operator
`BigNumber("-20") * BigNumber("-5") => BigNumber("100")`
### `/`
Division operator
`BigNumber("10") / BigNumber("-2") => BigNumber("-5")`
### `==`
Equal to operator
`BigNumber("24") == BigNumber("24") => true`
### `>`
Greater than operator
`BigNumber("2") > BigNumber("6") => false`
### `<`
Less than operator
`BigNumber("2") < BigNumber("6") => true`
### `>=`
Greater than or equal to operator
`BigNumber("34") >= BigNumber("22") => true`
### `<=`
Less than or equal to operator
`BigNumber("383") <= BigNumber("383") => true`
### `=`
Assignment operator
`BigNumber c("3") = BigNumber("8") => BigNumber("8")`
### `+=`
Adds and assigns to the BigNumber
`BigNumber c("4") += BigNumber("3") => BigNumber("7")`
### `-=`
Subtracts and assigns to the BigNumber
`BigNumber c("28") -= BigNumber("3") => BigNumber("25")`
### `*=`
Multiplies and assigns to the BigNumber
`BigNumber c("3") *= BigNumber("4") => BigNumber("12")`
### `/=`
Divides and assigns to the BigNumber
`BigNumber c("30") /= BigNumber("30") => BigNumer("1")`
### `++ (Prefix)`
Increments the BigNumber and returns the newly incremented number
`++BigNumber("10") => BigNumber("11")`
### `-- (Prefix)`
Decrements the BigNumber and returns the newly decremented number
`--BigNumber("34") => BigNumber("33")`
### `++ (Postfix)`
Increments the BigNumber but returns the original value
`BigNumber("20")++ => BigNumber("20")`
### `-- (Postfix)`
Decrements the BigNumber but returns the original value
`BigNumber("14")-- => BigNumber("14")`
### `[]`
Indexing operator
`BigNumber d("26")[1] => 6`
## License
This project is under the [Apache License](https://github.com/Limeoats/BigNumber/blob/master/LICENSE.md).
## Credit
The BigNumber class was created by [Mark Guerra](http://www.twitter.com/Limeoats). Visit
[Limeoats.com](http://www.limeoats.com) for more information.

View File

@ -0,0 +1,360 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Mark Guerra
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
* OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef BIGNUMBER_H
#define BIGNUMBER_H
#include <vector>
#include <string>
#include <iostream>
/**
* BigNumber class
*/
class BigNumber {
public:
//@{
/**
* BigNumber constructor
* @param number - The initial value of the BigNumber
*/
BigNumber(std::string number);
BigNumber(long long number);
//@}
/**
* Add another BigNumber to the current instance
* @param other - The other BigNumber
* @return The sum of the two BigNumbers
*/
BigNumber add(BigNumber other);
/**
* Subtract another BigNumber from the current instance
* @param other - The other BigNumber
* @return The difference of the two BigNumbers
*/
BigNumber subtract(BigNumber other);
/**
* Multiply the current instance by another BigNumber
* @param other - The other BigNumber
* @return The product of the two BigNumbers
*/
BigNumber multiply(BigNumber other);
/**
* Divide the current instance by another BigNumber
* @param other - The other BigNumber
* @return The quotient of the two BigNumbers
*/
BigNumber divide(BigNumber other);
/**
* Raise the current instance to the power of an exponent
* @param exponent - The power to be raised by
* @return - The resulting BigNumber after exponentiation
*/
BigNumber pow(int exponent);
/**
* Get the string value of the current instance
* @return The BigNumber as a string
*/
std::string getString();
/**
* Set the value of the current instance with a string
* @param newStr - The new value for the BigNumber
* @return The BigNumber with the new value
*/
BigNumber setString(const std::string &newStr);
/**
* Negates the current instance
* @return The BigNumber after negation
*/
BigNumber negate();
BigNumber trimLeadingZeros();
//@{
/**
* Check if another BigNumber is equal to the current instance
* @param other - The other BigNumber
* @return True if equal, otherwise false
*/
bool equals(const BigNumber &other);
bool equals(const long long &other);
bool equals(const std::string &other);
//@}
/**
* Get the number of digits in the current instance
* @return The number of digits
*/
unsigned int digits();
/**
* Get whether or not the current instance is a negative number
* @return True if negative, otherwise false
*/
bool isNegative() const;
/**
* Get whether or not the current instance is a positive number
* @return True if positive, otherwise false
*/
bool isPositive();
/**
* Get whether or not the current instance is an even number
* @return True if even, otherwise false
*/
bool isEven();
/**
* Get whether or not the current instance is an odd number
* @return True if odd, otherwise false
*/
bool isOdd();
/**
* Get the absolute value of the current instance
* @return The absolute value of the BigNumber
*/
BigNumber abs() const;
/**
* Output stream operator
* @param os The output stream
* @param num The current instance
* @return The output stream with the current instance
*/
friend std::ostream &operator<<(std::ostream &os, const BigNumber &num);
//@{
/**
* Addition operator
* @param b1 - The current instance
* @param b2 - The number being added
* @return The sum of the two numbers
*/
friend BigNumber operator+(BigNumber b1, const BigNumber &b2);
friend BigNumber operator+(BigNumber b1, const long long &b2);
friend BigNumber operator+(BigNumber b1, const std::string &b2);
//@}
//@{
/**
* Subtraction operator
* @param b1 - The current instance
* @param b2 - The number being subtracted
* @return The difference of the two numbers
*/
friend BigNumber operator-(BigNumber b1, const BigNumber &b2);
friend BigNumber operator-(BigNumber b1, const long long &b2);
friend BigNumber operator-(BigNumber b1, const std::string &b2);
//@}
//@{
/**
* Multiplication operator
* @param b1 - The current instance
* @param b2 - The number being multiplied by
* @return The product of the two numbers
*/
friend BigNumber operator*(BigNumber b1, const BigNumber &b2);
friend BigNumber operator*(BigNumber b1, const long long &b2);
friend BigNumber operator*(BigNumber b1, const std::string &b2);
//@}
//@{
/**
* Division operator
* @param b1 - The current instance
* @param b2 - The number being divided by
* @return The quotient of the two numbers
*/
friend BigNumber operator/(BigNumber b1, const BigNumber &b2);
friend BigNumber operator/(BigNumber b1, const long long &b2);
friend BigNumber operator/(BigNumber b1, const std::string &b2);
//@}
/**
* Exponent operator
* @param b1 - The current instance
* @param b2 - The exponent
* @return The value after exponentiation
*/
friend BigNumber operator^(BigNumber b1, const int &b2);
//@{
/**
* Equality operator
* @param b1 - The current instance
* @param b2 - Another value
* @return True if equal, otherwise false
*/
friend bool operator==(BigNumber b1, const BigNumber &b2);
friend bool operator==(BigNumber b1, const long long &b2);
friend bool operator==(BigNumber b1, const std::string &b2);
//@}
/**
* Greater-than operator
* @param b1 - The current instance
* @param b2 - Another BigNumber
* @return True if current instance is greater, otherwise false
*/
friend bool operator>(BigNumber b1, const BigNumber &b2);
/**
* Less-than operator
* @param b1 - The current instance
* @param b2 - Another BigNumber
* @return True if current instance is less, otherwise false
*/
friend bool operator<(BigNumber b1, const BigNumber &b2);
/**
* Greater-than or equal-to operator
* @param b1 - The current instance
* @param b2 - Another BigNumber
* @return True if current instance is greater or equal, otherwise false
*/
friend bool operator>=(BigNumber b1, const BigNumber &b2);
/**
* Less-than or equal-to operator
* @param b1 - The current instance
* @param b2 - Another BigNumber
* @return True if current instance is less or equal, otherwise false
*/
friend bool operator<=(BigNumber b1, const BigNumber &b2);
//@{
/**
* Assignment operator
* @param other - The new value for the BigNumber
* @return A BigNumber containing the new value
*/
BigNumber& operator=(const BigNumber &other);
BigNumber& operator=(const long long &other);
BigNumber& operator=(const std::string &other);
//@}
//@{
/**
* Addition assignment operator\n
* Adds and assigns a value to the current instance
* @param other - The value being added
* @return The new value after addition and assignment
*/
BigNumber& operator+=(const BigNumber &other);
BigNumber& operator+=(const long long &other);
BigNumber& operator+=(const std::string &other);
//@}
//@{
/**
* Subtraction assignment operator\n
* Subtracts and assigns a value to the current instance
* @param other - The value being subtracted
* @return The new value after subtraction and assignment
*/
BigNumber& operator-=(const BigNumber &other);
BigNumber& operator-=(const long long &other);
BigNumber& operator-=(const std::string &other);
//@}
//@{
/**
* Multiplication assignment operator\n
* Multiplies and assigns a value to the current instance
* @param other - The value being multiplied
* @return The new value after multiplication and assignment
*/
BigNumber& operator*=(const BigNumber &other);
BigNumber& operator*=(const long long &other);
BigNumber& operator*=(const std::string &other);
//@}
//@{
/**
* Division assignment operator\n
* Divides and assigns a value to the current instance
* @param other - The value being divided
* @return The new value after division and assignment
*/
BigNumber& operator/=(const BigNumber &other);
BigNumber& operator/=(const long long &other);
BigNumber& operator/=(const std::string &other);
//@}
/**
* Pre-increment operator
* @return The incremented BigNumber
*/
BigNumber& operator++();
/**
* Pre-decrement operator
* @return The decremented BigNumber
*/
BigNumber& operator--();
/**
* Post-increment operator
* @return The incremented BigNumber
*/
BigNumber operator++(int);
/**
* Post-decrement operator
* @return The decremented BigNumber
*/
BigNumber operator--(int);
/**
* The index operator
* @param index The position being looked at
* @return The number at the specified position in the BigNumber string
*/
unsigned int operator[](int index);
private:
std::string _numberString; //The big number represented as a string
//Methods
BigNumber addll(const long long &other);
BigNumber addstr(const std::string &other);
BigNumber subtractll(const long long &other);
BigNumber subtractstr(const std::string &other);
BigNumber multiplyll(const long long &other);
BigNumber multiplystr(const std::string &other);
BigNumber dividell(const long long &other);
BigNumber dividestr(const std::string &other);
};
#endif

View File

@ -0,0 +1,192 @@
////////////////////////////
//To make sure assert works:
#ifdef NDEBUG
#undef NDEBUG
#endif
////////////////////////////
#include "src/bignumber.h"
#include <assert.h>
int main() {
//Addition
assert((BigNumber(50) + BigNumber(32)).getString() == "82");
assert((BigNumber(5) + BigNumber(622)).getString() == "627");
assert((BigNumber("-33") + BigNumber("8")).getString() == "-25");
assert((BigNumber("15535") + BigNumber("0")).getString() == "15535");
assert((BigNumber("126") + BigNumber("39285")).getString() == "39411");
assert((BigNumber("0") + BigNumber("0")).getString() == "0");
assert(BigNumber(5) + 10 == 15);
assert(BigNumber("-41") + 40 == -1);
BigNumber ad1(600);
ad1 += 50;
ad1 += "50";
assert(ad1.getString() == "700");
assert(ad1 == 700);
//Subtraction
assert((BigNumber("50") - BigNumber("32")).getString() == "18");
assert((BigNumber("50") - BigNumber("60")).getString() == "-10");
assert((BigNumber("0") - BigNumber("46")).getString() == "-46");
assert((BigNumber("50") - BigNumber("50")).getString() == "0");
assert((BigNumber("482847") - BigNumber("89787941")).getString() == "-89305094");
assert((BigNumber("6828") - BigNumber("1")).getString() == "6827");
assert((BigNumber("100") - BigNumber("50")).getString() == "50");
assert((BigNumber("42") - BigNumber("49")).getString() == "-7");
assert((BigNumber("100") - BigNumber("5")) == 95);
BigNumber sb1 = 200;
sb1 -= 40;
assert(sb1 == 160);
sb1 = sb1 - 180;
assert(sb1 == "-20");
sb1 -= "20";
assert(sb1 == BigNumber(-40));
//Multiplication
assert((BigNumber("4") * BigNumber("12")).getString() == "48");
assert((BigNumber("3002") * BigNumber("1")).getString() == "3002");
assert((BigNumber("99") * BigNumber("0")).getString() == "0");
assert((BigNumber("-5") * BigNumber("5")).getString() == "-25");
assert((BigNumber("-33") * BigNumber("-2")).getString() == "66");
assert((BigNumber("283") * BigNumber("382871")).getString() == "108352493");
BigNumber ml1 = 4;
ml1 *= 6;
assert(ml1 == "24");
ml1 = BigNumber(5) * 6;
assert(ml1 == 30);
ml1 *= "5000";
assert(ml1 == 150000);
//Division
assert(BigNumber("25").divide(BigNumber("5")) == 5);
assert(BigNumber("48").divide(BigNumber("6")) == 8);
assert(BigNumber("100").divide(BigNumber("5")) == 20);
BigNumber dv1 = 100;
dv1 /= 25;
assert(dv1 == 4);
dv1 = dv1 / dv1;
assert(dv1 == 1);
dv1 /= 1;
assert(dv1 == 1);
dv1 = -5;
dv1 /= 5;
assert(dv1 == -1);
dv1 = 3000;
dv1 /= 300;
assert(dv1 == 10);
dv1 = 25485;
dv1 /= 5;
assert(dv1 == "5097");
//Exponentiation
assert((BigNumber("2").pow(3)).getString() == "8");
assert((BigNumber("1").pow(38)).getString() == "1");
assert((BigNumber("5").pow(2)).getString() == "25");
assert((BigNumber("10").pow(10)).getString() == "10000000000");
assert((BigNumber("5").pow(1)).getString() == "5");
assert((BigNumber("5").pow(0)).getString() == "1");
assert((BigNumber("-5").pow(2)).getString() == "25");
//Equals
assert(BigNumber("4") == BigNumber("4"));
assert(BigNumber("-3") == BigNumber("-3"));
assert(BigNumber("0") == BigNumber("0"));
assert(BigNumber("938283828178273") == BigNumber("938283828178273"));
//Greater than
assert(BigNumber("5") > BigNumber("2"));
assert(BigNumber("30") > BigNumber("-40"));
assert(BigNumber("-5") > BigNumber("-10"));
assert(BigNumber("0") > BigNumber("-1"));
//Less than
assert(BigNumber("10") < BigNumber("20"));
assert(BigNumber("-5") < BigNumber("0"));
assert(BigNumber("30") < BigNumber("30000"));
//Greater than or equal to
assert(BigNumber("5") >= BigNumber("0"));
assert(BigNumber("-5") >= BigNumber("-5"));
assert(BigNumber("-5") >= BigNumber("-10"));
assert(BigNumber("0") >= BigNumber("0"));
assert(BigNumber("32") >= BigNumber("-32"));
assert(BigNumber("2") >= BigNumber("0001"));
//Less than or equal to
assert(BigNumber("5") <= BigNumber("10"));
assert(BigNumber("0") <= BigNumber("0"));
assert(BigNumber("-5") <= BigNumber("0"));
assert(BigNumber("30") <= BigNumber("30"));
assert(BigNumber("400") <= BigNumber("392342"));
//Index
assert(BigNumber("423")[1] == 2);
assert(BigNumber("0")[0] == 0);
assert(BigNumber("-5")[1] == 5);
//Even
assert(BigNumber("426").isEven());
assert(BigNumber("-20").isEven());
//Odd
assert(BigNumber("83").isOdd());
assert(BigNumber("-27").isOdd());
//Positive
assert(BigNumber("38").isPositive());
//Negative
assert(BigNumber("-28382").isNegative());
//Increment/Decrement operators
assert(BigNumber("5")--.getString() == "5");
assert((--BigNumber("5")).getString() == "4");
assert(BigNumber("10")++.getString() == "10");
assert((++BigNumber("10")).getString() == "11");
BigNumber a("10");
a++;
assert(a.getString() == "11");
++a;
assert(a.getString() == "12");
a--;
assert(a.getString() == "11");
--a;
assert(a.getString() == "10");
//Absolute value
assert(BigNumber("45").abs().getString() == "45");
assert(BigNumber("-325").abs().getString() == "325");
//Digits
assert(BigNumber("28374765").digits() == 8);
assert(BigNumber("-3092").digits() == 4);
//Set string
assert(BigNumber("234").setString("-45").getString() == "-45");
//Assignment operator
BigNumber c(10);
c = 5;
assert(c == 5);
assert(c == BigNumber(5));
assert(c == BigNumber("5"));
c = "83833";
assert(c == 83833);
assert(c == BigNumber(83833));
assert(c == BigNumber("83833"));
//Equals testing
BigNumber d(40);
assert(d == 40);
assert(d == "40");
assert(d == BigNumber("40"));
assert(d == BigNumber(40));
d = 40;
assert(d == 40);
d = "40";
assert(d == 40);
std::cout << "BigNumber ran successfully." << std::endl;
}

View File

@ -0,0 +1,609 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Mark Guerra
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
* OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <sstream>
#include <stack>
#include <iostream>
#include "bignumber.h"
BigNumber::BigNumber(std::string number) :
_numberString(number)
{
}
BigNumber::BigNumber(long long number) :
_numberString(std::to_string(number))
{}
BigNumber BigNumber::add(BigNumber other) {
BigNumber b1 = other > *this ? other : *this;
BigNumber b2 = other > *this ? *this : other;
if (b1.isNegative() || b2.isNegative()) {
if (b1.isNegative() && b2.isNegative()) {
return b1.negate().add(b2.negate()).negate();
}
else if (b1.isNegative() && !b2.isNegative()) {
return b1.negate().subtract(b2).negate();
}
else {
return b2.negate().subtract(b1).negate();
}
}
std::string results;
int carry = 0;
int diff = int(b1._numberString.size() - b2._numberString.size());
for (int i = 0; i < diff; ++i) {
b2._numberString.insert(b2._numberString.begin(), '0');
}
for (int i = int(b1._numberString.size() - 1); i >= 0; --i) {
int sum = (b1._numberString[i] - '0') + (b2._numberString[i] - '0') + carry;
carry = 0;
if (sum <= 9 || i == 0) {
results.insert(0, std::to_string(sum));
}
else {
results.insert(0, std::to_string(sum % 10));
carry = 1;
}
}
return BigNumber(results);
}
BigNumber BigNumber::addll(const long long &other) {
return this->add(BigNumber(other));
}
BigNumber BigNumber::addstr(const std::string &other) {
return this->add(BigNumber(other));
}
BigNumber BigNumber::subtract(BigNumber other) {
BigNumber b1 = *this, b2 = other;
if (b1.isNegative() || b2.isNegative()) {
if (b1.isNegative() && b2.isNegative()) {
return b1.negate().add(b2.negate()).negate();
}
else if (b1.isNegative() && !b2.isNegative()) {
return b1.negate().add(b2).negate();
}
else {
return b2.negate().add(b1);
}
}
std::string results;
int n = 0, p = 0;
bool takeOffOne = false;
bool shouldBeTen = false;
if (b1 < b2) {
//Negative answer
std::string t = b2.subtract(*this).negate().getString();
for (unsigned int i = 1; i < t.length(); ++i) {
if (t[i] != '0') break;
t.erase(1, 1);
}
return BigNumber(t);
}
//This next if-block fixes the case where the digit difference is greater than 1
//100 - 5 is an example. This code adds 0's to make it, for example, 100 - 05, which
//allows the rest of the subtraction code to work.
if (b1._numberString.size() - b2.getString().size() > 1) {
for (unsigned long i = 0; i < b1._numberString.size() - b2.getString().size() - 1; ++i) {
b2._numberString.insert(b2._numberString.begin(), '0');
}
}
int i = int(b1._numberString.size() - 1);
for (int j = int(b2._numberString.size() - 1); j >= 0; --j) {
if (((b1._numberString[i] - '0') < (b2._numberString[j] - '0')) && i > 0) {
n = char((b1._numberString[i] - '0') + 10);
takeOffOne = true;
if (j > 0 || b1._numberString[i - 1] != '0') {
p = char((b1._numberString[i - 1] - '0') - 1);
if (p == -1) {
p = 9;
shouldBeTen = true;
}
takeOffOne = false;
}
if (shouldBeTen) {
int index = i - 1;
for (int a = i - 1; (b1._numberString[a] - '0') == 0; --a) {
b1._numberString[a] = static_cast<char>(p + '0');
--index;
}
int t = (b1._numberString[index] - '0') - 1;
b1._numberString[index] = static_cast<char>(t + '0');
}
b1._numberString[i - 1] = static_cast<char>(p + '0');
shouldBeTen = false;
}
std::stringstream ss;
if (((b1._numberString[i] - '0') == (b2._numberString[j] - '0'))) {
ss << "0";
}
else {
if (n <= 0) {
ss << ((b1._numberString[i] - '0') - (b2._numberString[j] - '0'));
}
else {
ss << (n - (b2._numberString[j] - '0'));
}
}
results.insert(0, ss.str());
--i;
n = 0;
}
if (takeOffOne) {
std::string number = "";
for (int j = b1._numberString.length() - b2._numberString.length() - 1; j >= 0; --j) {
if (b1._numberString[j] == '0') {
number += "0";
continue;
}
else {
number.insert(number.begin(), b1._numberString[j]);
int t = atoi(number.c_str());
--t;
b1._numberString.replace(0, number.size(), std::to_string(t));
break;
}
}
}
while (i >= 0) {
std::stringstream ss;
if (i == 0) {
if (b1._numberString[i] - '0' != 0) {
ss << (b1._numberString[i] - '0');
results.insert(0, ss.str());
}
}
else {
ss << (b1._numberString[i] - '0');
results.insert(0, ss.str());
}
--i;
}
//In the case of all 0's, we only want to return one of them
if (results.find_first_not_of('0') == std::string::npos) {
results = "0";
}
else if (results[0] == '0') {
int index = results.find_first_not_of('0');
results = results.substr(index, results.length() - 1);
}
return BigNumber(results);
}
BigNumber BigNumber::subtractll(const long long &other) {
return this->subtract(BigNumber(other));
}
BigNumber BigNumber::subtractstr(const std::string &other) {
return this->subtract(BigNumber(other));
}
BigNumber BigNumber::multiply(BigNumber other) {
BigNumber b1 = other > *this ? other : *this;
BigNumber b2 = other > *this ? *this : other;
if (b1.isNegative() || b2.isNegative()) {
if (b1.isNegative() && b2.isNegative()) {
return b1.negate().multiply(b2.negate());
}
else if (b1.isNegative() && !b2.isNegative()) {
return b1.negate().multiply(b2).negate();
}
else {
return b2.negate().multiply(b1).negate();
}
}
if (b1 == 0 || b2 == 0) return 0;
int carry = 0;
int zeroCounter = 0;
BigNumber b = 0;
for (unsigned int i = 0; i < b1._numberString.size() - b2._numberString.size(); ++i) {
b2._numberString.insert(b2._numberString.begin(), '0');
}
for (long long int i = (b2._numberString.size() - 1); i >= 0; --i) {
std::string rr;
for (long long int j = int(b1._numberString.size() - 1); j >= 0; --j) {
int val = ((b2._numberString[i] - '0') * (b1._numberString[j] - '0')) + carry;
carry = 0;
if (val > 9 && j != 0) {
carry = val / 10;
rr.insert(0, std::to_string(val % 10));
}
else {
rr.insert(0, std::to_string(val));
}
}
if (zeroCounter > 0) {
for (int x = 0; x < zeroCounter; ++x) {
rr.append("0");
}
}
++zeroCounter;
b += BigNumber(rr);
}
if (b._numberString.find_first_not_of('0') != std::string::npos) {
b.setString(b._numberString.erase(0, b._numberString.find_first_not_of('0')));
}
else {
//In the case of all 0's, we only want to return one of them
b.setString("0");
}
return b;
}
BigNumber BigNumber::multiplyll(const long long &other) {
if (other == 0)
return 0;
if (other == 1)
return *this;
auto original = *this;
for (auto i = 0; i < other - 1; ++i) {
*this += original;
}
return *this;
}
BigNumber BigNumber::multiplystr(const std::string &other) {
return this->multiply(BigNumber(other));
}
BigNumber BigNumber::divide(BigNumber other) {
if (other == 0) {
std::cerr << "You cannot divide by 0!" << std::endl;
}
BigNumber b1 = *this, b2 = other;
bool sign = false;
if (b1.isNegative() && b2.isNegative()) {
b1.negate();
b2.negate();
}
else if (b1.isNegative() && !b2.isNegative()) {
b1.negate();
sign = true;
}
else if (!b1.isNegative() && b2.isNegative()) {
b2.negate();
sign = true;
}
BigNumber quotient = 0;
while (b1 >= b2) {
b1 -= b2;
++quotient;
}
if (sign) quotient.negate();
return quotient;
}
BigNumber BigNumber::dividell(const long long &other) {
return this->divide(BigNumber(other));
}
BigNumber BigNumber::dividestr(const std::string &other) {
return this->divide(BigNumber(other));
}
BigNumber BigNumber::pow(int exponent) {
if (exponent < 0) std::cerr << "Powers less than 0 are not supported" << std::endl;
if (exponent == 0) return BigNumber("1");
if (exponent == 1) return *this;
BigNumber result = 1, base = *this;
while (exponent) {
if (exponent & 1) {
result *= base;
}
exponent >>= 1;
base *= base;
}
return result;
}
std::string BigNumber::getString() {
return this->_numberString;
}
BigNumber BigNumber::setString(const std::string &newStr) {
this->_numberString = newStr;
return *this;
}
BigNumber BigNumber::negate() {
if (this->_numberString[0] == '-') {
this->_numberString.erase(0, 1);
}
else {
this->_numberString.insert(this->_numberString.begin(), '-');
}
return *this;
}
BigNumber BigNumber::trimLeadingZeros() {
BigNumber b = *this;
if (b._numberString.find_first_not_of('0') != std::string::npos) {
b.setString(b._numberString.erase(0, b._numberString.find_first_not_of('0')));
}
return b;
}
bool BigNumber::equals(const BigNumber &other) {
return this->_numberString == other._numberString;
}
bool BigNumber::equals(const long long &other) {
return this->getString() == std::to_string(other);
}
bool BigNumber::equals(const std::string &other) {
return this->getString() == other;
}
unsigned int BigNumber::digits() {
return this->_numberString.length() - static_cast<int>(this->isNegative());
}
bool BigNumber::isNegative() const {
return this->_numberString[0] == '-';
}
bool BigNumber::isPositive() {
return !this->isNegative();
}
bool BigNumber::isEven() {
return this->_numberString[this->_numberString.length() - 1] % 2 == 0;
}
bool BigNumber::isOdd() {
return !this->isEven();
}
BigNumber BigNumber::abs() const {
return BigNumber(this->_numberString.substr(static_cast<unsigned int>(this->isNegative())));
}
std::ostream &operator<<(std::ostream &os, const BigNumber &num) {
os << num._numberString;
return os;
}
BigNumber operator+(BigNumber b1, const BigNumber &b2) {
return b1.add(b2);
}
BigNumber operator+(BigNumber b1, const long long &b2) {
return b1.addll(b2);
}
BigNumber operator+(BigNumber b1, const std::string &b2) {
return b1.addstr(b2);
}
BigNumber operator-(BigNumber b1, const BigNumber &b2) {
return b1.subtract(b2);
}
BigNumber operator-(BigNumber b1, const long long &b2) {
return b1.subtractll(b2);
}
BigNumber operator-(BigNumber b1, const std::string &b2) {
return b1.subtractstr(b2);
}
BigNumber operator*(BigNumber b1, const BigNumber &b2) {
return b1.multiply(b2);
}
BigNumber operator*(BigNumber b1, const long long &b2) {
return b1.multiplyll(b2);
}
BigNumber operator*(BigNumber b1, const std::string &b2) {
return b1.multiplystr(b2);
}
BigNumber operator/(BigNumber b1, const BigNumber &b2) {
return b1.divide(b2);
}
BigNumber operator/(BigNumber b1, const long long &b2) {
return b1.dividell(b2);
}
BigNumber operator/(BigNumber b1, const std::string &b2) {
return b1.dividestr(b2);
}
BigNumber operator^(BigNumber b1, const int &b2) {
return b1.pow(b2);
}
bool operator==(BigNumber b1, const BigNumber &b2) {
return b1.equals(b2);
}
bool operator==(BigNumber b1, const long long &b2) {
return b1.equals(b2);
}
bool operator==(BigNumber b1, const std::string &b2) {
return b1.equals(b2);
}
bool operator>(BigNumber b1, const BigNumber &b2) {
if (b1.isNegative() || b2.isNegative()) {
if (b1.isNegative() && b2.isNegative()) {
BigNumber bt = b2;
b1._numberString.erase(0, 1);
bt._numberString.erase(0, 1);
return b1 < bt;
}
else {
return !(b1.isNegative() && !b2.isNegative());
}
}
b1 = b1.trimLeadingZeros();
auto c = BigNumber(b2);
c = c.trimLeadingZeros();
if (b1 == c) {
return false;
}
if (b1._numberString.size() > c._numberString.size()) {
return true;
}
else if (c._numberString.size() > b1._numberString.size()) {
return false;
}
else {
for (unsigned int i = 0; i < b1._numberString.size(); ++i) {
if (b1[i] == static_cast<unsigned int>(c._numberString[i] - '0')) {
continue;
}
return b1[i] > static_cast<unsigned int>(c._numberString[i] - '0');
}
}
return false;
}
bool operator<(BigNumber b1, const BigNumber &b2) {
return !(b1 == b2) && !(b1 > b2);
}
bool operator>=(BigNumber b1, const BigNumber &b2) {
return b1 > b2 || b1 == b2;
}
bool operator<=(BigNumber b1, const BigNumber &b2) {
return b1 < b2 || b1 == b2;
}
unsigned int BigNumber::operator[](int index) {
if (this->_numberString[index] == '-') {
std::cerr << "You cannot get the negative sign from the number" << std::endl;
}
return static_cast<unsigned int>(this->_numberString[index] - '0');
}
BigNumber& BigNumber::operator=(const BigNumber &other) {
this->_numberString = other._numberString;
return *this;
}
BigNumber& BigNumber::operator=(const long long &other) {
this->_numberString = std::to_string(other);
return *this;
}
BigNumber& BigNumber::operator=(const std::string &other) {
this->_numberString = other;
return *this;
}
BigNumber& BigNumber::operator+=(const BigNumber &other) {
*this = *this + other;
return *this;
}
BigNumber& BigNumber::operator+=(const long long &other) {
*this = *this + other;
return *this;
}
BigNumber& BigNumber::operator+=(const std::string &other) {
*this = *this + other;
return *this;
}
BigNumber& BigNumber::operator-=(const BigNumber &other) {
*this = *this - other;
return *this;
}
BigNumber& BigNumber::operator-=(const long long &other) {
*this = *this - other;
return *this;
}
BigNumber& BigNumber::operator-=(const std::string &other) {
*this = *this - other;
return *this;
}
BigNumber& BigNumber::operator*=(const BigNumber &other) {
*this = *this * other;
return *this;
}
BigNumber& BigNumber::operator*=(const long long &other) {
*this = *this * other;
return *this;
}
BigNumber& BigNumber::operator*=(const std::string &other) {
*this = *this * other;
return *this;
}
BigNumber& BigNumber::operator/=(const BigNumber &other) {
*this = *this / other;
return *this;
}
BigNumber& BigNumber::operator/=(const long long &other) {
*this = *this / other;
return *this;
}
BigNumber& BigNumber::operator/=(const std::string &other) {
*this = *this / other;
return *this;
}
BigNumber& BigNumber::operator++() {
*this += BigNumber("1");
return *this;
}
BigNumber& BigNumber::operator--() {
*this -= BigNumber("1");
return *this;
}
BigNumber BigNumber::operator++(int) {
BigNumber t(this->getString());
++(*this);
return t;
}
BigNumber BigNumber::operator--(int) {
BigNumber t(this->getString());
--(*this);
return t;
}

View File

@ -0,0 +1,360 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Mark Guerra
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
* OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef BIGNUMBER_H
#define BIGNUMBER_H
#include <vector>
#include <string>
#include <iostream>
/**
* BigNumber class
*/
class BigNumber {
public:
//@{
/**
* BigNumber constructor
* @param number - The initial value of the BigNumber
*/
BigNumber(std::string number);
BigNumber(long long number);
//@}
/**
* Add another BigNumber to the current instance
* @param other - The other BigNumber
* @return The sum of the two BigNumbers
*/
BigNumber add(BigNumber other);
/**
* Subtract another BigNumber from the current instance
* @param other - The other BigNumber
* @return The difference of the two BigNumbers
*/
BigNumber subtract(BigNumber other);
/**
* Multiply the current instance by another BigNumber
* @param other - The other BigNumber
* @return The product of the two BigNumbers
*/
BigNumber multiply(BigNumber other);
/**
* Divide the current instance by another BigNumber
* @param other - The other BigNumber
* @return The quotient of the two BigNumbers
*/
BigNumber divide(BigNumber other);
/**
* Raise the current instance to the power of an exponent
* @param exponent - The power to be raised by
* @return - The resulting BigNumber after exponentiation
*/
BigNumber pow(int exponent);
/**
* Get the string value of the current instance
* @return The BigNumber as a string
*/
std::string getString();
/**
* Set the value of the current instance with a string
* @param newStr - The new value for the BigNumber
* @return The BigNumber with the new value
*/
BigNumber setString(const std::string &newStr);
/**
* Negates the current instance
* @return The BigNumber after negation
*/
BigNumber negate();
BigNumber trimLeadingZeros();
//@{
/**
* Check if another BigNumber is equal to the current instance
* @param other - The other BigNumber
* @return True if equal, otherwise false
*/
bool equals(const BigNumber &other);
bool equals(const long long &other);
bool equals(const std::string &other);
//@}
/**
* Get the number of digits in the current instance
* @return The number of digits
*/
unsigned int digits();
/**
* Get whether or not the current instance is a negative number
* @return True if negative, otherwise false
*/
bool isNegative() const;
/**
* Get whether or not the current instance is a positive number
* @return True if positive, otherwise false
*/
bool isPositive();
/**
* Get whether or not the current instance is an even number
* @return True if even, otherwise false
*/
bool isEven();
/**
* Get whether or not the current instance is an odd number
* @return True if odd, otherwise false
*/
bool isOdd();
/**
* Get the absolute value of the current instance
* @return The absolute value of the BigNumber
*/
BigNumber abs() const;
/**
* Output stream operator
* @param os The output stream
* @param num The current instance
* @return The output stream with the current instance
*/
friend std::ostream &operator<<(std::ostream &os, const BigNumber &num);
//@{
/**
* Addition operator
* @param b1 - The current instance
* @param b2 - The number being added
* @return The sum of the two numbers
*/
friend BigNumber operator+(BigNumber b1, const BigNumber &b2);
friend BigNumber operator+(BigNumber b1, const long long &b2);
friend BigNumber operator+(BigNumber b1, const std::string &b2);
//@}
//@{
/**
* Subtraction operator
* @param b1 - The current instance
* @param b2 - The number being subtracted
* @return The difference of the two numbers
*/
friend BigNumber operator-(BigNumber b1, const BigNumber &b2);
friend BigNumber operator-(BigNumber b1, const long long &b2);
friend BigNumber operator-(BigNumber b1, const std::string &b2);
//@}
//@{
/**
* Multiplication operator
* @param b1 - The current instance
* @param b2 - The number being multiplied by
* @return The product of the two numbers
*/
friend BigNumber operator*(BigNumber b1, const BigNumber &b2);
friend BigNumber operator*(BigNumber b1, const long long &b2);
friend BigNumber operator*(BigNumber b1, const std::string &b2);
//@}
//@{
/**
* Division operator
* @param b1 - The current instance
* @param b2 - The number being divided by
* @return The quotient of the two numbers
*/
friend BigNumber operator/(BigNumber b1, const BigNumber &b2);
friend BigNumber operator/(BigNumber b1, const long long &b2);
friend BigNumber operator/(BigNumber b1, const std::string &b2);
//@}
/**
* Exponent operator
* @param b1 - The current instance
* @param b2 - The exponent
* @return The value after exponentiation
*/
friend BigNumber operator^(BigNumber b1, const int &b2);
//@{
/**
* Equality operator
* @param b1 - The current instance
* @param b2 - Another value
* @return True if equal, otherwise false
*/
friend bool operator==(BigNumber b1, const BigNumber &b2);
friend bool operator==(BigNumber b1, const long long &b2);
friend bool operator==(BigNumber b1, const std::string &b2);
//@}
/**
* Greater-than operator
* @param b1 - The current instance
* @param b2 - Another BigNumber
* @return True if current instance is greater, otherwise false
*/
friend bool operator>(BigNumber b1, const BigNumber &b2);
/**
* Less-than operator
* @param b1 - The current instance
* @param b2 - Another BigNumber
* @return True if current instance is less, otherwise false
*/
friend bool operator<(BigNumber b1, const BigNumber &b2);
/**
* Greater-than or equal-to operator
* @param b1 - The current instance
* @param b2 - Another BigNumber
* @return True if current instance is greater or equal, otherwise false
*/
friend bool operator>=(BigNumber b1, const BigNumber &b2);
/**
* Less-than or equal-to operator
* @param b1 - The current instance
* @param b2 - Another BigNumber
* @return True if current instance is less or equal, otherwise false
*/
friend bool operator<=(BigNumber b1, const BigNumber &b2);
//@{
/**
* Assignment operator
* @param other - The new value for the BigNumber
* @return A BigNumber containing the new value
*/
BigNumber& operator=(const BigNumber &other);
BigNumber& operator=(const long long &other);
BigNumber& operator=(const std::string &other);
//@}
//@{
/**
* Addition assignment operator\n
* Adds and assigns a value to the current instance
* @param other - The value being added
* @return The new value after addition and assignment
*/
BigNumber& operator+=(const BigNumber &other);
BigNumber& operator+=(const long long &other);
BigNumber& operator+=(const std::string &other);
//@}
//@{
/**
* Subtraction assignment operator\n
* Subtracts and assigns a value to the current instance
* @param other - The value being subtracted
* @return The new value after subtraction and assignment
*/
BigNumber& operator-=(const BigNumber &other);
BigNumber& operator-=(const long long &other);
BigNumber& operator-=(const std::string &other);
//@}
//@{
/**
* Multiplication assignment operator\n
* Multiplies and assigns a value to the current instance
* @param other - The value being multiplied
* @return The new value after multiplication and assignment
*/
BigNumber& operator*=(const BigNumber &other);
BigNumber& operator*=(const long long &other);
BigNumber& operator*=(const std::string &other);
//@}
//@{
/**
* Division assignment operator\n
* Divides and assigns a value to the current instance
* @param other - The value being divided
* @return The new value after division and assignment
*/
BigNumber& operator/=(const BigNumber &other);
BigNumber& operator/=(const long long &other);
BigNumber& operator/=(const std::string &other);
//@}
/**
* Pre-increment operator
* @return The incremented BigNumber
*/
BigNumber& operator++();
/**
* Pre-decrement operator
* @return The decremented BigNumber
*/
BigNumber& operator--();
/**
* Post-increment operator
* @return The incremented BigNumber
*/
BigNumber operator++(int);
/**
* Post-decrement operator
* @return The decremented BigNumber
*/
BigNumber operator--(int);
/**
* The index operator
* @param index The position being looked at
* @return The number at the specified position in the BigNumber string
*/
unsigned int operator[](int index);
private:
std::string _numberString; //The big number represented as a string
//Methods
BigNumber addll(const long long &other);
BigNumber addstr(const std::string &other);
BigNumber subtractll(const long long &other);
BigNumber subtractstr(const std::string &other);
BigNumber multiplyll(const long long &other);
BigNumber multiplystr(const std::string &other);
BigNumber dividell(const long long &other);
BigNumber dividestr(const std::string &other);
};
#endif

View File

@ -0,0 +1,61 @@
// fig03_05.cpp
// Integer ranges and arbitrary-precision integers.
#include <iostream>
#include "bignumber.h"
using namespace std;
int main() {
// use the maximum long long fundamental type value in calculations
const long long value1{9'223'372'036'854'775'807LL}; // long long max
cout << "long long value1: " << value1
<< "\nvalue1 - 1: " << value1 - 1 // OK
<< "\nvalue1 + 1: " << value1 + 1; // result is undefined
// use an arbitrary-precision integer
const BigNumber value2{value1};
cout << "\n\nBigNumber value2: " << value2
<< "\nvalue2 - 1: " << value2 - 1 // OK
<< "\nvalue2 + 1: " << value2 + 1; // OK
// powers of 100,000,000 with long long
long long value3{100'000'000};
cout << "\n\nvalue3: " << value3;
int counter{2};
while (counter <= 5) {
value3 *= 100'000'000; // quickly exceeds maximum long long value
cout << "\nvalue3 to the power " << counter << ": " << value3;
++counter;
}
// powers of 100,000,000 with BigNumber
BigNumber value4{100'000'000};
cout << "\n\nvalue4: " << value4 << "\n";
counter = 2;
while (counter <= 5) {
cout << "value4.pow(" << counter << "): "
<< value4.pow(counter) << "\n";
++counter;
}
cout << "\n";
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/

View File

@ -0,0 +1,29 @@
// fig03_06.cpp
// C++20 string formatting.
#include <iostream>
#include <fmt/format.h> // C++20: This will be #include <format>
using namespace std;
using namespace fmt; // not needed in C++20
int main() {
string student{"Paul"};
int grade{87};
cout << format("{}'s grade is {}\n", student, grade);
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,176 @@
// Formatting library for C++
//
// Copyright (c) 2012 - 2016, Victor Zverovich
// All rights reserved.
//
// For the license information refer to format.h.
#include "fmt/format-inl.h"
FMT_BEGIN_NAMESPACE
namespace internal {
template <typename T>
int format_float(char* buf, std::size_t size, const char* format, int precision,
T value) {
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
if (precision > 100000)
throw std::runtime_error(
"fuzz mode - avoid large allocation inside snprintf");
#endif
// Suppress the warning about nonliteral format string.
int (*snprintf_ptr)(char*, size_t, const char*, ...) = FMT_SNPRINTF;
return precision < 0 ? snprintf_ptr(buf, size, format, value)
: snprintf_ptr(buf, size, format, precision, value);
}
struct sprintf_specs {
int precision;
char type;
bool alt : 1;
template <typename Char>
constexpr sprintf_specs(basic_format_specs<Char> specs)
: precision(specs.precision), type(specs.type), alt(specs.alt) {}
constexpr bool has_precision() const { return precision >= 0; }
};
// This is deprecated and is kept only to preserve ABI compatibility.
template <typename Double>
char* sprintf_format(Double value, internal::buffer<char>& buf,
sprintf_specs specs) {
// Buffer capacity must be non-zero, otherwise MSVC's vsnprintf_s will fail.
FMT_ASSERT(buf.capacity() != 0, "empty buffer");
// Build format string.
enum { max_format_size = 10 }; // longest format: %#-*.*Lg
char format[max_format_size];
char* format_ptr = format;
*format_ptr++ = '%';
if (specs.alt || !specs.type) *format_ptr++ = '#';
if (specs.precision >= 0) {
*format_ptr++ = '.';
*format_ptr++ = '*';
}
if (std::is_same<Double, long double>::value) *format_ptr++ = 'L';
char type = specs.type;
if (type == '%')
type = 'f';
else if (type == 0 || type == 'n')
type = 'g';
#if FMT_MSC_VER
if (type == 'F') {
// MSVC's printf doesn't support 'F'.
type = 'f';
}
#endif
*format_ptr++ = type;
*format_ptr = '\0';
// Format using snprintf.
char* start = nullptr;
char* decimal_point_pos = nullptr;
for (;;) {
std::size_t buffer_size = buf.capacity();
start = &buf[0];
int result =
format_float(start, buffer_size, format, specs.precision, value);
if (result >= 0) {
unsigned n = internal::to_unsigned(result);
if (n < buf.capacity()) {
// Find the decimal point.
auto p = buf.data(), end = p + n;
if (*p == '+' || *p == '-') ++p;
if (specs.type != 'a' && specs.type != 'A') {
while (p < end && *p >= '0' && *p <= '9') ++p;
if (p < end && *p != 'e' && *p != 'E') {
decimal_point_pos = p;
if (!specs.type) {
// Keep only one trailing zero after the decimal point.
++p;
if (*p == '0') ++p;
while (p != end && *p >= '1' && *p <= '9') ++p;
char* where = p;
while (p != end && *p == '0') ++p;
if (p == end || *p < '0' || *p > '9') {
if (p != end) std::memmove(where, p, to_unsigned(end - p));
n -= static_cast<unsigned>(p - where);
}
}
}
}
buf.resize(n);
break; // The buffer is large enough - continue with formatting.
}
buf.reserve(n + 1);
} else {
// If result is negative we ask to increase the capacity by at least 1,
// but as std::vector, the buffer grows exponentially.
buf.reserve(buf.capacity() + 1);
}
}
return decimal_point_pos;
}
} // namespace internal
template FMT_API char* internal::sprintf_format(double, internal::buffer<char>&,
sprintf_specs);
template FMT_API char* internal::sprintf_format(long double,
internal::buffer<char>&,
sprintf_specs);
template struct FMT_INSTANTIATION_DEF_API internal::basic_data<void>;
// Workaround a bug in MSVC2013 that prevents instantiation of format_float.
int (*instantiate_format_float)(double, int, internal::float_specs,
internal::buffer<char>&) =
internal::format_float;
#ifndef FMT_STATIC_THOUSANDS_SEPARATOR
template FMT_API internal::locale_ref::locale_ref(const std::locale& loc);
template FMT_API std::locale internal::locale_ref::get<std::locale>() const;
#endif
// Explicit instantiations for char.
template FMT_API std::string internal::grouping_impl<char>(locale_ref);
template FMT_API char internal::thousands_sep_impl(locale_ref);
template FMT_API char internal::decimal_point_impl(locale_ref);
template FMT_API void internal::buffer<char>::append(const char*, const char*);
template FMT_API void internal::arg_map<format_context>::init(
const basic_format_args<format_context>& args);
template FMT_API std::string internal::vformat<char>(
string_view, basic_format_args<format_context>);
template FMT_API format_context::iterator internal::vformat_to(
internal::buffer<char>&, string_view, basic_format_args<format_context>);
template FMT_API int internal::snprintf_float(double, int,
internal::float_specs,
internal::buffer<char>&);
template FMT_API int internal::snprintf_float(long double, int,
internal::float_specs,
internal::buffer<char>&);
template FMT_API int internal::format_float(double, int, internal::float_specs,
internal::buffer<char>&);
template FMT_API int internal::format_float(long double, int,
internal::float_specs,
internal::buffer<char>&);
// Explicit instantiations for wchar_t.
template FMT_API std::string internal::grouping_impl<wchar_t>(locale_ref);
template FMT_API wchar_t internal::thousands_sep_impl(locale_ref);
template FMT_API wchar_t internal::decimal_point_impl(locale_ref);
template FMT_API void internal::buffer<wchar_t>::append(const wchar_t*,
const wchar_t*);
template FMT_API std::wstring internal::vformat<wchar_t>(
wstring_view, basic_format_args<wformat_context>);
FMT_END_NAMESPACE

View File

@ -0,0 +1,30 @@
// fig04_01.cpp
// Counter-controlled iteration with the while iteration statement.
#include <iostream>
using namespace std;
int main() {
int counter{1}; // declare and initialize control variable
while (counter <= 10) { // loop-continuation condition
cout << counter << " ";
++counter; // increment control variable
}
cout << "\n";
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
*************************************************************************/

View File

@ -0,0 +1,30 @@
// fig04_02.cpp
// Counter-controlled iteration with the for iteration statement.
#include <iostream>
using namespace std;
int main() {
// for statement header includes initialization,
// loop-continuation condition and increment
for (int counter{1}; counter <= 10; ++counter) {
cout << counter << " ";
}
cout << "\n";
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
*************************************************************************/

View File

@ -0,0 +1,31 @@
// fig04_03.cpp
// Summing integers with the for statement.
#include <iostream>
using namespace std;
int main() {
int total{0};
// total even integers from 2 through 20
for (int number{2}; number <= 20; number += 2) {
total += number;
}
cout << "Sum is " << total << "\n";
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
*************************************************************************/

View File

@ -0,0 +1,45 @@
// fig04_04.cpp
// Compound-interest calculations with for.
#include <iostream>
#include <iomanip>
#include <cmath> // for pow function
using namespace std;
int main() {
// set floating-point number format
cout << fixed << setprecision(2);
double principal{1000.00}; // initial amount before interest
double rate{0.05}; // interest rate
cout << "Initial principal: " << principal << "\n";
cout << " Interest rate: " << rate << "\n";
// display headers
cout << "\nYear" << setw(20) << "Amount on deposit" << "\n";
// calculate amount on deposit for each of ten years
for (int year{1}; year <= 10; ++year) {
// calculate amount on deposit at the end of the specified year
double amount{principal * pow(1.0 + rate, year)} ;
// display the year and the amount
cout << setw(4) << year << setw(20) << amount << "\n";
}
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
*************************************************************************/

View File

@ -0,0 +1,31 @@
// fig04_05.cpp
// do...while iteration statement.
#include <iostream>
using namespace std;
int main() {
int counter{1};
do {
cout << counter << " ";
++counter;
} while (counter <= 10); // end do...while
cout << "\n";
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
*************************************************************************/

View File

@ -0,0 +1,90 @@
// fig04_06.cpp
// Using a switch statement to count letter grades.
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
int total{0}; // sum of grades
int gradeCounter{0}; // number of grades entered
int aCount{0}; // count of A grades
int bCount{0}; // count of B grades
int cCount{0}; // count of C grades
int dCount{0}; // count of D grades
int fCount{0}; // count of F grades
cout << "Enter the integer grades in the range 0-100.\n"
<< "Type the end-of-file indicator to terminate input:\n"
<< " On UNIX/Linux/macOS type <Ctrl> d then press Enter\n"
<< " On Windows type <Ctrl> z then press Enter\n";
int grade;
// loop until user enters the end-of-file indicator
while (cin >> grade) {
total += grade; // add grade to total
++gradeCounter; // increment number of grades
// increment appropriate letter-grade counter
switch (grade / 10) {
case 9: // grade was between 90
case 10: // and 100, inclusive
++aCount;
break; // exits switch
case 8: // grade was between 80 and 89
++bCount;
break; // exits switch
case 7: // grade was between 70 and 79
++cCount;
break; // exits switch
case 6: // grade was between 60 and 69
++dCount;
break; // exits switch
default: // grade was less than 60
++fCount;
break; // optional; exits switch anyway
} // end switch
} // end while
// set floating-point number format
cout << fixed << setprecision(2);
// display grade report
cout << "\nGrade Report:\n";
// if user entered at least one grade...
if (gradeCounter != 0) {
// calculate average of all grades entered
double average{static_cast<double>(total) / gradeCounter};
// output summary of results
cout << "Total of the " << gradeCounter << " grades entered is "
<< total << "\nClass average is " << average
<< "\nNumber of students who received each grade:"
<< "\nA: " << aCount << "\nB: " << bCount << "\nC: " << cCount
<< "\nD: " << dCount << "\nF: " << fCount << "\n";
}
else { // no grades were entered, so output appropriate message
cout << "No grades were entered" << "\n";
}
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
*************************************************************************/

View File

@ -0,0 +1,36 @@
// fig04_07.cpp
// C++17 if statements with initializers.
#include <iostream>
using namespace std;
int main() {
if (int value{7}; value == 7) {
cout << "value is " << value << "\n";
}
else {
cout << "value is not 7; it is " << value << "\n";
}
if (int value{13}; value == 9) {
cout << "value is " << value << "\n";
}
else {
cout << "value is not 9; it is " << value << "\n";
}
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/

View File

@ -0,0 +1,38 @@
// fig04_07_with_error.cpp
// C++17 if statements with initializers.
#include <iostream>
using namespace std;
int main() {
if (int value{7}; value == 7) {
cout << "value is " << value << "\n";
}
else {
cout << "value is not 7; it is " << value << "\n";
}
if (int value{13}; value == 9) {
cout << "value is " << value << "\n";
}
else {
cout << "value is not 9; it is " << value << "\n";
}
cout << value;
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/

View File

@ -0,0 +1,34 @@
// fig04_08.cpp
// break statement exiting a for statement.
#include <iostream>
using namespace std;
int main() {
int count; // control variable also used after loop
for (count = 1; count <= 10; ++count) { // loop 10 times
if (count == 5) {
break; // terminates for loop if count is 5
}
cout << count << " ";
}
cout << "\nBroke out of loop at count = " << count << "\n";
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
*************************************************************************/

View File

@ -0,0 +1,32 @@
// fig04_09.cpp
// continue statement terminating an iteration of a for statement.
#include <iostream>
using namespace std;
int main() {
for (int count{1}; count <= 10; ++count) { // loop 10 times
if (count == 5) {
continue; // skip remaining code in loop body if count is 5
}
cout << count << " ";
}
cout << "\nUsed continue to skip printing 5" << "\n";
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
*************************************************************************/

View File

@ -0,0 +1,43 @@
// fig04_10.cpp
// Logical operators.
#include <iostream>
#include <fmt/format.h>
using namespace std;
using namespace fmt;
int main() {
// create truth table for && (logical AND) operator
cout << "Logical AND (&&)\n"
<< format("false && false: {}\n", false && false)
<< format("false && true: {}\n", false && true)
<< format("true && false: {}\n", true && false)
<< format("true && true: {}\n\n", true && true);
// create truth table for || (logical OR) operator
cout << "Logical OR (||)\n"
<< format("false || false: {}\n", false || false)
<< format("false || true: {}\n", false || true)
<< format("true || false: {}\n", true || false)
<< format("true || true: {}\n\n", true || true);
// create truth table for ! (logical negation) operator
cout << "Logical negation (!)\n"
<< format("!false: {}\n", !false)
<< format("!true: {}\n", !true);
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
*************************************************************************/

View File

@ -0,0 +1,70 @@
// fig04_11.cpp
// Using the miniz-cpp header-only library to write and read a ZIP file.
#include <iostream>
#include <string>
#include "zip_file.hpp"
using namespace std;
int main() {
cout << "Enter a ZIP file name: ";
string zipFileName;
getline(cin, zipFileName); // inputs a line of text
// string literals separated only by whitespace are combined
// into a single string by the compiler
string content{
"This chapter introduces all but one of the remaining control "
"statements--the for, do...while, switch, break and continue "
"statements. We explore the essentials of counter-controlled "
"iteration. We use compound-interest calculations to begin "
"investigating the issues of processing monetary amounts. First, "
"we discuss the representational errors associated with "
"floating-point types. We use a switch statement to count the "
"number of A, B, C, D and F grade equivalents in a set of "
"numeric grades. We show C++17's enhancements that allow you to "
"initialize one or more variables of the same type in the "
"headers of if and switch statements."};
cout << "\ncontent.length(): " << content.length();
miniz_cpp::zip_file output; // create zip_file object
// write content into a text file in output
output.writestr("intro.txt", content); // create file in ZIP
output.save(zipFileName); // save output to zipFileName
miniz_cpp::zip_file input{zipFileName}; // load zipFileName
// display input's file name and directory listing
cout << "\n\nZIP file's name: " << input.get_filename()
<< "\n\nZIP file's directory listing:\n";
input.printdir();
// display info about the compressed intro.txt file
miniz_cpp::zip_info info{input.getinfo("intro.txt")};
cout << "\nFile name: " << info.filename
<< "\nOriginal size: " << info.file_size
<< "\nCompressed size: " << info.compress_size;
// original file contents
string extractedContent{input.read(info)};
cout << "\n\nOriginal contents of intro.txt:\n"
<< extractedContent << "\n";
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
*************************************************************************/

View File

@ -0,0 +1,40 @@
// fig04_12.cpp
// Compound-interest example with C++20 text formatting.
#include <iostream>
#include <cmath> // for pow function
#include "fmt/format.h" // in C++20, this will be #include <format>
using namespace std;
using namespace fmt; // not needed in C++20
int main() {
double principal{1000.00}; // initial amount before interest
double rate{0.05}; // interest rate
cout << format("Initial principal: {:>7.2f}\n", principal)
<< format(" Interest rate: {:>7.2f}\n", rate);
// display headers
cout << format("\n{}{:>20}\n", "Year", "Amount on deposit");
// calculate amount on deposit for each of ten years
for (int year{1}; year <= 10; ++year) {
double amount{principal * pow(1.0 + rate, year)};
cout << format("{:>4d}{:>20.2f}\n", year, amount);
}
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/

View File

@ -0,0 +1,111 @@
// cipher.h
// Deitel implementation of the Vigenère cipher.
#pragma once
#include <algorithm>
#include <array>
#include <iostream>
#include <string>
#include <cctype>
#include <stdexcept>
#include <gsl/gsl>
class Cipher {
public:
Cipher() noexcept {
std::array<char, size> alphabet{};
for (int i{0}; i < size; ++i) {
alphabet.at(i) = 'a' + i;
}
square.at(0) = alphabet;
for (int row{1}; row < size; ++row) {
std::rotate(alphabet.begin(), alphabet.begin() + 1, alphabet.end());
square.at(row) = alphabet;
}
}
std::string encrypt(const std::string& plainText,
const std::string& secret) {
checkKey(secret); // ensure only letters in secret
std::string cipherText{};
size_t keyCounter{0};
for (size_t i{0}; i < plainText.length(); ++i) {
const bool upper = std::isupper(plainText.at(i));
const char current = std::tolower(plainText.at(i));
if ('a' <= current && current <= 'z') {
const int row{tolower(secret.at(keyCounter)) - 'a'};
keyCounter = (keyCounter + 1) % secret.length();
const int col{current - 'a'};
const char substitute{square.at(row).at(col)};
cipherText += (upper ? std::toupper(substitute) : substitute);
}
else {
cipherText += plainText.at(i); // pass through numbers and punctuation
}
}
return cipherText;
}
std::string decrypt(const std::string& text,
const std::string& secret) {
checkKey(secret); // ensure only letters in secret
std::string plainText;
size_t keyCounter{0};
for (size_t i{0}; i < text.length(); ++i) {
const bool upper = std::isupper(text.at(i));
const char current = std::tolower(text.at(i));
if ('a' <= current && current <= 'z') {
const int row{std::tolower(secret.at(keyCounter)) - 'a'};
keyCounter = (keyCounter + 1) % secret.length();
int column{-1};
for (size_t col{0}; col < square.at(row).size(); ++col) {
if (square.at(row).at(col) == current) {
column = gsl::narrow_cast<int>(col);
break;
}
}
const char original{gsl::narrow_cast<char>('a' + column)};
plainText += (upper ? std::toupper(original) : original);
}
else {
plainText += current; // pass through numbers and punctuation
}
}
return plainText;
}
private:
constexpr static int size{26};
std::array<std::array<char, 26>, 26> square;
// checks that secret key contains only letters
void checkKey(std::string secret) {
for (int i{0}; i < secret.size(); ++i) {
if (tolower(secret.at(i)) < 'a' || tolower(secret.at(i)) > 'z') {
throw std::invalid_argument(
"key must contain only letters A-Z or a-z");
}
}
}
};
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/

View File

@ -0,0 +1,49 @@
// fig05_01.cpp
// maximum function with a function prototype.
#include <iostream>
#include <iomanip>
using namespace std;
int maximum(int x, int y, int z); // function prototype
int main() {
cout << "Enter three integer values: ";
int int1, int2, int3;
cin >> int1 >> int2 >> int3;
// invoke maximum
cout << "The maximum integer value is: "
<< maximum(int1, int2, int3) << '\n';
}
// returns the largest of three integers
int maximum(int x, int y, int z) {
int maximumValue{x}; // assume x is the largest to start
// determine whether y is greater than maximumValue
if (y > maximumValue) {
maximumValue = y; // make y the new maximumValue
}
// determine whether z is greater than maximumValue
if (z > maximumValue) {
maximumValue = z; // make z the new maximumValue
}
return maximumValue;
}
/*************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
*************************************************************************/

View File

@ -0,0 +1,36 @@
// fig05_02.cpp
// Producing random integers in the range 1 through 6.
#include <iostream>
#include <random> // contains C++11 random-number generation features
using namespace std;
int main() {
// engine that produces random numbers
default_random_engine engine{};
// distribution that produces the int values 1-6 with equal likelihood
uniform_int_distribution randomDie{1, 6};
// display 10 random die rolls
for (int counter{1}; counter <= 10; ++counter) {
cout << randomDie(engine) << " ";
}
cout << '\n';
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/

View File

@ -0,0 +1,72 @@
// fig05_03.cpp
// Rolling a six-sided die 60,000,000 times.
#include <fmt/format.h>
#include <iostream>
#include <random>
using namespace std;
int main() {
// set up random-number generation
default_random_engine engine{};
uniform_int_distribution randomDie{1, 6};
int frequency1{0}; // count of 1s rolled
int frequency2{0}; // count of 2s rolled
int frequency3{0}; // count of 3s rolled
int frequency4{0}; // count of 4s rolled
int frequency5{0}; // count of 5s rolled
int frequency6{0}; // count of 6s rolled
// summarize results of 60,000,000 rolls of a die
for (int roll{1}; roll <= 60'000'000; ++roll) {
// determine roll value 1-6 and increment appropriate counter
switch (const int face{randomDie(engine)}) {
case 1:
++frequency1; // increment the 1s counter
break;
case 2:
++frequency2; // increment the 2s counter
break;
case 3:
++frequency3; // increment the 3s counter
break;
case 4:
++frequency4; // increment the 4s counter
break;
case 5:
++frequency5; // increment the 5s counter
break;
case 6:
++frequency6; // increment the 6s counter
break;
default: // invalid value
cout << "Program should never get here!";
break;
}
}
cout << fmt::format("{:>4}{:>13}\n", "Face", "Frequency"); // headers
cout << fmt::format("{:>4d}{:>13d}\n", 1, frequency1)
<< fmt::format("{:>4d}{:>13d}\n", 2, frequency2)
<< fmt::format("{:>4d}{:>13d}\n", 3, frequency3)
<< fmt::format("{:>4d}{:>13d}\n", 4, frequency4)
<< fmt::format("{:>4d}{:>13d}\n", 5, frequency5)
<< fmt::format("{:>4d}{:>13d}\n", 6, frequency6);
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/

View File

@ -0,0 +1,40 @@
// fig05_04.cpp
// Randomizing the die-rolling program.
#include <iostream>
#include <iomanip>
#include <random>
using namespace std;
int main() {
unsigned int seed{0}; // stores the seed entered by the user
cout << "Enter seed: ";
cin >> seed;
// set up random-number generation
default_random_engine engine{seed}; // seed the engine
uniform_int_distribution randomDie{1, 6};
// display 10 random die rolls
for (int counter{1}; counter <= 10; ++counter) {
cout << randomDie(engine) << " ";
}
cout << '\n';
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/

View File

@ -0,0 +1,86 @@
// fig05_05.cpp
// Craps simulation.
#include <fmt/format.h>
#include <iostream>
#include <random>
using namespace std;
int rollDice(); // rolls dice, calculates and displays sum
int main() {
// scoped enumeration with constants that represent the game status
enum class Status {keepRolling, won, lost};
int myPoint{0}; // point if no win or loss on first roll
Status gameStatus{Status::keepRolling}; // game is not over
// determine game status and point (if needed) based on first roll
switch (const int sumOfDice{rollDice()}) {
case 7: // win with 7 on first roll
case 11: // win with 11 on first roll
gameStatus = Status::won;
break;
case 2: // lose with 2 on first roll
case 3: // lose with 3 on first roll
case 12: // lose with 12 on first roll
gameStatus = Status::lost;
break;
default: // did not win or lose, so remember point
myPoint = sumOfDice; // remember the point
cout << fmt::format("Point is {}\n", myPoint);
break; // optional (but recommended) at end of switch
}
// while game is not complete
while (Status::keepRolling == gameStatus) { // not won or lost
// roll dice again and determine game status
if (const int sumOfDice{rollDice()}; sumOfDice == myPoint) {
gameStatus = Status::won;
}
else if (sumOfDice == 7) { // lose by rolling 7 before point
gameStatus = Status::lost;
}
}
// display won or lost message
if (Status::won == gameStatus) {
cout << "Player wins\n";
}
else {
cout << "Player loses\n";
}
}
// roll dice, calculate sum and display results
int rollDice() {
// set up random-number generation
static random_device rd; // used to seed the default_random_engine
static default_random_engine engine{rd()}; // rd() produces a seed
static uniform_int_distribution randomDie{1, 6};
const int die1{randomDie(engine)}; // first die roll
const int die2{randomDie(engine)}; // second die roll
const int sum{die1 + die2}; // compute sum of die values
// display results of this roll
cout << fmt::format("Player rolled {} + {} = {}\n", die1, die2, sum);
return sum;
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/

View File

@ -0,0 +1,79 @@
// fig05_06.cpp
// Scoping example.
#include <iostream>
using namespace std;
void useLocal(); // function prototype
void useStaticLocal(); // function prototype
void useGlobal(); // function prototype
int x{1}; // global variable
int main() {
cout << "global x in main is " << x << '\n';
const int x{5}; // local variable to main
cout << "local x in main's outer scope is " << x << '\n';
{ // block starts a new scope
const int x{7}; // hides both x in outer scope and global x
cout << "local x in main's inner scope is " << x << '\n';
}
cout << "local x in main's outer scope is " << x << '\n';
useLocal(); // useLocal has local x
useStaticLocal(); // useStaticLocal has static local x
useGlobal(); // useGlobal uses global x
useLocal(); // useLocal reinitializes its local x
useStaticLocal(); // static local x retains its prior value
useGlobal(); // global x also retains its prior value
cout << "\nlocal x in main is " << x << '\n';
}
// useLocal reinitializes local variable x during each call
void useLocal() {
int x{25}; // initialized each time useLocal is called
cout << "\nlocal x is " << x << " on entering useLocal\n";
++x;
cout << "local x is " << x << " on exiting useLocal\n";
}
// useStaticLocal initializes static local variable x only the
// first time the function is called; value of x is saved
// between calls to this function
void useStaticLocal() {
static int x{50}; // initialized first time useStaticLocal is called
cout << "\nlocal static x is " << x
<< " on entering useStaticLocal\n";
++x;
cout << "local static x is " << x <<
" on exiting useStaticLocal\n";
}
// useGlobal modifies global variable x during each call
void useGlobal() {
cout << "\nglobal x is " << x << " on entering useGlobal\n";
x *= 10;
cout << "global x is " << x << " on exiting useGlobal\n";
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/

View File

@ -0,0 +1,37 @@
// fig05_07.cpp
// inline function that calculates the volume of a cube.
#include <iostream>
using namespace std;
// Definition of inline function cube. Definition of function appears
// before function is called, so a function prototype is not required.
// First line of function definition also acts as the prototype.
inline double cube(double side) {
return side * side * side; // calculate cube
}
int main() {
double sideValue; // stores value entered by user
cout << "Enter the side length of your cube: ";
cin >> sideValue; // read value from user
// calculate cube of sideValue and display result
cout << "Volume of cube with side "
<< sideValue << " is " << cube(sideValue) << '\n';
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/

View File

@ -0,0 +1,51 @@
// fig05_08.cpp
// Passing arguments by value and by reference.
#include <iostream>
using namespace std;
int squareByValue(int number); // prototype (for value pass)
void squareByReference(int& numberRef); // prototype (for reference pass)
int main() {
int x{2}; // value to square using squareByValue
int z{4}; // value to square using squareByReference
// demonstrate squareByValue
cout << "x = " << x << " before squareByValue\n";
cout << "Value returned by squareByValue: "
<< squareByValue(x) << endl;
cout << "x = " << x << " after squareByValue\n\n";
// demonstrate squareByReference
cout << "z = " << z << " before squareByReference\n";
squareByReference(z);
cout << "z = " << z << " after squareByReference\n";
}
// squareByValue multiplies number by itself, stores the
// result in number and returns the new value of number
int squareByValue(int number) {
return number *= number; // caller's argument not modified
}
// squareByReference multiplies numberRef by itself and stores the result
// in the variable to which numberRef refers in function main
void squareByReference(int& numberRef) {
numberRef *= numberRef; // caller's argument modified
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/

View File

@ -0,0 +1,46 @@
// fig05_09.cpp
// Using default arguments.
#include <iostream>
using namespace std;
// function prototype that specifies default arguments
int boxVolume(int length = 1, int width = 1, int height = 1);
int main() {
// no arguments--use default values for all dimensions
cout << "The default box volume is: " << boxVolume();
// specify length; default width and height
cout << "\n\nThe volume of a box with length 10,\n"
<< "width 1 and height 1 is: " << boxVolume(10);
// specify length and width; default height
cout << "\n\nThe volume of a box with length 10,\n"
<< "width 5 and height 1 is: " << boxVolume(10, 5);
// specify all arguments
cout << "\n\nThe volume of a box with length 10,\n"
<< "width 5 and height 2 is: " << boxVolume(10, 5, 2)
<< '\n';
}
// function boxVolume calculates the volume of a box
int boxVolume(int length, int width, int height) {
return length * width * height;
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/

View File

@ -0,0 +1,31 @@
// fig05_10.cpp
// Unary scope resolution operator.
#include <iostream>
using namespace std;
const int number{7}; // global variable named number
int main() {
const double number{10.5}; // local variable named number
// display values of local and global variables
cout << "Local double value of number = " << number
<< "\nGlobal int value of number = " << ::number << '\n';
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/

View File

@ -0,0 +1,38 @@
// fig05_11.cpp
// Overloaded square functions.
#include <iostream>
using namespace std;
// function square for int values
int square(int x) {
cout << "square of integer " << x << " is ";
return x * x;
}
// function square for double values
double square(double y) {
cout << "square of double " << y << " is ";
return y * y;
}
int main() {
cout << square(7); // calls int version
cout << '\n';
cout << square(7.5); // calls double version
cout << '\n';
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/

View File

@ -0,0 +1,40 @@
// fig05_12.cpp
// Name mangling to enable type-safe linkage.
// function square for int values
int square(int x) {
return x * x;
}
// function square for double values
double square(double y) {
return y * y;
}
// function that receives arguments of types
// int, float, char and int&
void nothing1(int a, float b, char c, int& d) { }
// function that receives arguments of types
// char, int, float& and double&
int nothing2(char a, int b, float& c, double& d) {
return 0;
}
int main() { }
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/

View File

@ -0,0 +1,50 @@
// fig05_14.cpp
// Function template maximum test program.
#include <iostream>
#include "maximum.h" // include definition of function template maximum
using namespace std;
int main() {
// demonstrate maximum with int values
cout << "Input three integer values: ";
int int1, int2, int3;
cin >> int1 >> int2 >> int3;
// invoke int version of maximum
cout << "The maximum integer value is: "
<< maximum(int1, int2, int3);
// demonstrate maximum with double values
cout << "\n\nInput three double values: ";
double double1, double2, double3;
cin >> double1 >> double2 >> double3;
// invoke double version of maximum
cout << "The maximum double value is: "
<< maximum(double1, double2, double3);
// demonstrate maximum with char values
cout << "\n\nInput three characters: ";
char char1, char2, char3;
cin >> char1 >> char2 >> char3;
// invoke char version of maximum
cout << "The maximum character value is: "
<< maximum(char1, char2, char3) << '\n';
} // end main
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/

View File

@ -0,0 +1,40 @@
// fig05_15.cpp
// Recursive function factorial.
#include <iostream>
#include <iomanip>
using namespace std;
long factorial(int number); // function prototype
int main() {
// calculate the factorials of 0 through 10
for (int counter{0}; counter <= 10; ++counter) {
cout << setw(2) << counter << "! = " << factorial(counter)
<< '\n';
}
}
// recursive definition of function factorial
long factorial(int number) {
if (number <= 1) { // test for base case
return 1; // base cases: 0! = 1 and 1! = 1
}
else { // recursion step
return number * factorial(number - 1);
}
}
/*************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
*************************************************************************/

View File

@ -0,0 +1,44 @@
// fig05_16.cpp
// Recursive function fibonacci.
#include <iostream>
using namespace std;
long fibonacci(long number); // function prototype
int main() {
// calculate the fibonacci values of 0 through 10
for (int counter{0}; counter <= 10; ++counter)
cout << "fibonacci(" << counter << ") = "
<< fibonacci(counter) << '\n';
// display higher fibonacci values
cout << "\nfibonacci(20) = " << fibonacci(20);
cout << "\nfibonacci(30) = " << fibonacci(30);
cout << "\nfibonacci(35) = " << fibonacci(35) << '\n';
}
// recursive function fibonacci
long fibonacci(long number) {
if ((0 == number) || (1 == number)) { // base cases
return number;
}
else { // recursion step
return fibonacci(number - 1) + fibonacci(number - 2);
}
}
/*************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
*************************************************************************/

View File

@ -0,0 +1,44 @@
// fig05_17.cpp
// Iterative function factorial.
#include <iostream>
#include <iomanip>
using namespace std;
long factorial(int number); // function prototype
int main() {
// calculate the factorials of 0 through 10
for (int counter{0}; counter <= 10; ++counter) {
cout << setw(2) << counter << "! = " << factorial(counter)
<< '\n';
}
}
// iterative method factorial
long factorial(int number) {
long result{1};
// iterative factorial calculation
for (int i{number}; i >= 1; --i) {
result *= i;
}
return result;
}
/*************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
*************************************************************************/

View File

@ -0,0 +1,47 @@
// fig05_18.cpp
// Encrypting and decrypting text with a Vigenère cipher.
#include "cipher.h"
#include <iostream>
#include <string>
using namespace std;
int main() {
string plainText;
cout << "Enter the text to encrypt:\n";
getline(cin, plainText);
string secretKey;
cout << "\nEnter the secret key:\n";
getline(cin, secretKey);
Cipher cipher;
// encrypt plainText using secretKey
string cipherText{cipher.encrypt(plainText, secretKey)};
cout << "\nEncrypted:\n " << cipherText << '\n';
// decrypt cipherText
cout << "\nDecrypted:\n "
<< cipher.decrypt(cipherText, secretKey) << '\n';
// decrypt ciphertext entered by the user
cout << "\nEnter the ciphertext to decipher:\n";
getline(cin, cipherText);
cout << "\nDecrypted:\n "
<< cipher.decrypt(cipherText, secretKey) << '\n';
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/

View File

@ -0,0 +1,33 @@
// Fig. 5.13: maximum.h
// Function template maximum header.
template <typename T> // or template<class T>
T maximum(T value1, T value2, T value3) {
T maximumValue{value1}; // assume value1 is maximum
// determine whether value2 is greater than maximumValue
if (value2 > maximumValue) {
maximumValue = value2;
}
// determine whether value3 is greater than maximumValue
if (value3 > maximumValue) {
maximumValue = value3;
}
return maximumValue;
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/

View File

@ -0,0 +1,55 @@
{
"files.associations": {
"array": "cpp",
"iostream": "cpp",
"atomic": "cpp",
"bit": "cpp",
"*.tcc": "cpp",
"cctype": "cpp",
"charconv": "cpp",
"clocale": "cpp",
"cmath": "cpp",
"compare": "cpp",
"concepts": "cpp",
"cstdarg": "cpp",
"cstddef": "cpp",
"cstdint": "cpp",
"cstdio": "cpp",
"cstdlib": "cpp",
"ctime": "cpp",
"cwchar": "cpp",
"cwctype": "cpp",
"deque": "cpp",
"string": "cpp",
"unordered_map": "cpp",
"vector": "cpp",
"exception": "cpp",
"algorithm": "cpp",
"functional": "cpp",
"iterator": "cpp",
"memory": "cpp",
"memory_resource": "cpp",
"numeric": "cpp",
"optional": "cpp",
"random": "cpp",
"string_view": "cpp",
"system_error": "cpp",
"tuple": "cpp",
"type_traits": "cpp",
"utility": "cpp",
"initializer_list": "cpp",
"iosfwd": "cpp",
"istream": "cpp",
"limits": "cpp",
"new": "cpp",
"numbers": "cpp",
"ostream": "cpp",
"ranges": "cpp",
"span": "cpp",
"stdexcept": "cpp",
"streambuf": "cpp",
"typeinfo": "cpp",
"variant": "cpp",
"format": "cpp"
}
}

Binary file not shown.

View File

@ -0,0 +1,49 @@
// fig06_01.cpp
// Initializing an array's elements to zeros and printing the array.
#include <format> // C++20: This will be #include <format>
#include <iostream>
#include <array>
int main() {
std::array<int, 5> values{}; // values is an array of 5 int values
// initialize elements of array values to 0
for (size_t i{0}; i < values.size(); ++i) {
values[i] = 0; // set element at location i to 0
}
std::cout << std::format("{:>7}{:>10}\n", "Element", "Value");
// output each array element's value
for (size_t i{0}; i < values.size(); ++i) {
std::cout << std::format("{:>7}{:>10}\n", i, values[i]);
}
std::cout << std::format("\n{:>7}{:>10}\n", "Element", "Value");
// access elements via the at member function
for (size_t i{0}; i < values.size(); ++i) {
std::cout << std::format("{:>7}{:>10}\n", i, values.at(i));
}
for (auto i : values){
std::cout << std::format("{:>7}{:>8}\n", i, values.at(i));
}
// accessing an element outside the array's bounds with at
values.at(10); // throws an exception
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/

View File

@ -0,0 +1,43 @@
// fig06_02.cpp
// Initializing an array in a declaration.
#include <format>
#include <iostream>
#include <array>
int main() {
std::array<int, 5> values{32, 27, 64, 18, 95}; // braced initializer
// output each array element's value
for (size_t i{0}; i < values.size(); ++i) {
std::cout << std::format("{} ", values.at(i));
}
std::cout << "\n\n";
// using class template argument deduction to determine values2's type
std::array values2{1.12, 2.2, 3.3, 4.4};
// output each array element's value
for (size_t i{0}; i < values2.size(); ++i) {
std::cout << std::format("{} ", values2.at(i));
}
std::cout << "\n";
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/

View File

@ -0,0 +1,50 @@
// fig06_03.cpp
// Using range-based for.
#include <format>
#include <iostream>
#include <array>
int main() {
std::array items{1, 2, 3, 4, 5}; // type inferred as array<int, 5>
// display items before modification
std::cout << "items before modification: ";
for (const int& item : items) { // item is a reference to a const int
std::cout << std::format("{} ", item);
}
// multiply the elements of items by 2
for (int& item : items) { // item is a reference to an int
item *= 2;
}
// display items after modification
std::cout << "\nitems after modification: ";
for (const int& item : items) {
std::cout << std::format("{} ", item);
}
// sum elements of items using range-based for with initialization
std::cout << "\n\ncalculating a running total of items' values:\n";
for (int runningTotal{0}; const int& item : items) {
runningTotal += item;
std::cout << std::format("item: {}; running total: {}\n",
item, runningTotal);
}
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/

View File

@ -0,0 +1,38 @@
// fig06_04.cpp
// Set array values to the even integers from 2 to 10.
#include <fmt/format.h>
#include <iostream>
#include <array>
int main() {
// constant can be used to specify array size
constexpr size_t arraySize{5}; // must initialize in declaration
std::array<int, arraySize> values{}; // array values has 5 elements
for (size_t i{0}; i < values.size(); ++i) { // set the values
values.at(i) = 2 + 2 * i;
}
// output contents of array values in tabular format
for (const int& value : values) {
std::cout << fmt::format("{} ", value);
}
std::cout << '\n';
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/

View File

@ -0,0 +1,34 @@
// fig06_05.cpp
// Compute the sum of an array's elements.
#include <fmt/format.h>
#include <iostream>
#include <array>
int main() {
std::array items{10, 20, 30, 40}; // type inferred as array<int, 4>
int total{0};
// sum the contents of items
for (const int& item : items) {
total += item;
}
std::cout << fmt::format("Total of array elements: {}\n", total);
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/

View File

@ -0,0 +1,49 @@
// fig06_06.cpp
// Printing a student grade distribution as a primitive bar chart.
#include <format>
#include <iostream>
#include <array>
int main() {
constexpr std::array frequencies{0, 0, 0, 0, 0, 0, 1, 2, 4, 2, 1};
std::cout << "Grade distribution:\n";
// for each element of frequencies, output a bar of the chart
for (int i{0}; const int& frequency : frequencies) {
// output bar labels ("00-09:", ..., "90-99:", "100:")
if (i < 10) {
std::cout << std::format("{:03d}-{:03d}: ",
i * 100, (i * 100) + 9);
}
else {
std::cout << std::format("{:>7d}: ", 100);
}
++i;
// print bar of asterisks
for (int stars{0}; stars < frequency; ++stars) {
std::cout << '*';
}
std::cout << '\n'; // start a new line of output
}
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/

View File

@ -0,0 +1,43 @@
// fig06_07.cpp
// Die-rolling program using an array instead of switch.
#include <format> // C++20: This will be #include <format>
#include <iostream>
#include <array>
#include <random>
int main() {
// set up random-number generation
std::random_device rd; // used to seed the default_random_engine
std::default_random_engine engine{rd()}; // rd() produces a seed
std::uniform_int_distribution randomDie{1, 6};
constexpr size_t arraySize{7}; // ignore element zero
std::array<int, arraySize> frequency{}; // initialize to 0s
// roll die 60,000,000 times; use die value as frequency index
for (int roll{1}; roll <= 60'000'000; ++roll) {
++frequency.at(randomDie(engine));
}
std::cout << std::format("{}{:>13}\n", "Face", "Frequency");
// output each array element's value
for (size_t face{1}; face < frequency.size(); ++face) {
std::cout << std::format("{:>4}{:>13}\n", face, frequency.at(face));
}
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/

View File

@ -0,0 +1,45 @@
// fig06_08.cpp
// Poll analysis program.
#include <format> // C++20: This will be #include <format>
#include <iostream>
#include <array>
int main() {
// place survey responses in array responses
constexpr std::array responses{
1, 2, 5, 4, 3, 5, 2, 1, 3, 1, 4, 3, 3, 3, 2, 3, 3, 2, 2, 5};
// initialize frequency counters to 0
constexpr size_t frequencySize{6}; // size of array frequency
std::array<int, frequencySize> frequency{};
// for each response in responses, use that value
// as frequency index to determine element to increment
for (const int& response : responses) {
++frequency[response];//.at(response);
}
std::cout << std::format("{}{:>12}\n", "Rating", "Frequency");
// output each array element's value
for (size_t rating{1}; rating < frequency.size(); ++rating) {
std::cout << std::format("{:>6}{:>12}\n",
rating, frequency.at(rating));
}
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/

View File

@ -0,0 +1,58 @@
// fig06_09.cpp
// Sorting and searching arrays.
#include <array>
#include <algorithm> // contains sort and binary_search
#include <format>
#include <iostream>
#include <string>
int main() {
using namespace std::string_literals; // enables string object literals
// colors is inferred to be an array<string, 7>
std::array colors{"red"s, "orange"s, "yellow"s,
"green"s, "blue"s, "indigo"s, "violet"s};
// output original array
std::cout << "Unsorted colors array:\n ";
for (const std::string& color : colors) {
std::cout << std::format("{} ", color);
}
// sort contents of colors
//std::sort(std::begin(colors), std::end(colors));
std::sort(colors.begin(), colors.end());
// output sorted array
std::cout << "\nSorted colors array:\n ";
for (const std::string& color : colors) {
std::cout << std::format("{} ", color);
}
// search for "indigo" in colors
bool found{std::binary_search(
std::begin(colors), std::end(colors), "indigo")};
std::cout << std::format("\n\n\"indigo\" {} found in colors array\n",
found ? "was" : "was not");
// search for "cyan" in colors
//found = std::binary_search( std::begin(colors), std::end(colors), "cyan");
found = std::binary_search( colors.begin(), colors.end(), "cyan");
std::cout << std::format("\"cyan\" {} found in colors array\n",
found ? "was" : "was not");
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/

View File

@ -0,0 +1,77 @@
// fig06_10.cpp
// Initializing multidimensional arrays.
#include <iostream>
#include <array>
#include <vector>
constexpr size_t rows{2};
constexpr size_t columns{3};
void printArray(const std::array<std::array<int, columns>, rows>& a);
template <typename T>
void printArrayTemplate(const T& a);
int main() {
constexpr std::array values1{std::array{1, 2, 3}, std::array{4, 5, 6}};
constexpr std::array values2{std::array{1, 2, 3}, std::array{4, 5, 0}};
constexpr std::array < std::array<int,3>, 2> values3{std::array{1, 2, 3}, std::array{4, 5, 6}};
std::vector < std::vector<int>> values3_vec{std::vector<int>{1, 2, 3}, std::vector<int>{4, 5, 6}};
std::cout << "values1 by row:\n";
printArray(values1);
std::cout << "\nvalues2 by row:\n";
printArray(values2);
std::cout << "\nvalues3 by row:\n";
printArrayTemplate(values3);
std::cout << "\nvalues3_vec by row:\n";
printArrayTemplate(values3_vec);
}
// output array with two rows and three columns
void printArray(const std::array<std::array<int, columns>, rows>& a) {
// loop through array's rows
for (const auto& row : a) {
// loop through columns of current row
for (const auto& element : row) {
std::cout << element << ' ';
}
std::cout << '\n'; // start new line of output
}
}
template <typename T>
void printArrayTemplate(const T& a) {
// loop through array's rows
for (const auto& row : a) {
// loop through columns of current row
for (const auto& element : row) {
std::cout << element << ' ';
}
std::cout << '\n'; // start new line of output
}
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/

View File

@ -0,0 +1,27 @@
// fig06_11.cpp
// Compute the sum of the elements of an array using accumulate.
#include <array>
#include <fmt/format.h>
#include <iostream>
#include <numeric>
int main() {
constexpr std::array integers{10, 20, 30, 40};
std::cout << fmt::format("Total of array elements: {}\n",
std::accumulate(std::begin(integers), std::end(integers), 0));
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/

View File

@ -0,0 +1,39 @@
// fig06_12.cpp
// Compute the product of an array's elements using accumulate.
#include <array>
#include <format>
#include <iostream>
#include <numeric>
int multiply(int x, int y) {
return x * y;
}
int main() {
constexpr std::array integers{1, 2, 3, 4, 5};
auto multiply_lambda = [](const auto& x, const auto& y) {return x * y; };
std::cout << std::format("Product of integers: {}\n", std::accumulate(
std::begin(integers), std::end(integers), 1, multiply));
std::cout << std::format("Product of integers with a lambda: {}\n",
std::accumulate(std::begin(integers), std::end(integers), 1,
multiply_lambda));
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/

View File

@ -0,0 +1,68 @@
// fig06_13.cpp
// Functional-style programming with C++20 ranges and views.
#include <array>
#include <fmt/format.h>
#include <iostream>
#include <numeric>
#include <ranges>
int main() {
// lambda to display results of range operations
auto showValues{
[](auto& values, const std::string& message) {
std::cout << fmt::format("{}: ", message);
for (const auto& value : values) {
std::cout << fmt::format("{} ", value);
}
std::cout << '\n';
}
};
auto values1{std::views::iota(1, 11)}; // generate integers 1-10
showValues(values1, "Generate integers 1-10");
// filter each value in values1, keeping only the even integers
auto values2{values1 |
std::views::filter([](const auto& x) {return x % 2 == 0;})};
showValues(values2, "Filtering even integers");
// map each value in values2 to its square
auto values3{
values2 | std::views::transform([](const auto& x) {return x * x;})};
showValues(values3, "Mapping even integers to squares");
// combine filter and transform to get squares of the even integers
auto values4{
values1 | std::views::filter([](const auto& x) {return x % 2 == 0;})
| std::views::transform([](const auto& x) {return x * x; })};
showValues(values4, "Squares of even integers");
// total the squares of the even integers
std::cout << fmt::format("Sum squares of even integers 2-10: {}\n",
std::accumulate(std::begin(values4), std::end(values4), 0));
// process a container's elements
constexpr std::array numbers{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
auto values5{
numbers | std::views::filter([](const auto& x) {return x % 2 == 0;})
| std::views::transform([](const auto& x) {return x * x; })};
showValues(values5, "Squares of even integers in array numbers");
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/

View File

@ -0,0 +1,123 @@
// fig06_14.cpp
// Demonstrating C++ standard library class template vector.
#include <iostream>
#include <vector>
#include <stdexcept>
void outputVector(const std::vector<int>& items); // display the vector
void inputVector(std::vector<int>& items); // input values into the vector
int main() {
std::vector<int> integers1(7); // 7-element vector<int>
std::vector<int> integers2(10); // 10-element vector<int>
// print integers1 size and contents
std::cout << "Size of vector integers1 is " << integers1.size()
<< "\nvector after initialization:";
outputVector(integers1);
// print integers2 size and contents
std::cout << "\nSize of vector integers2 is " << integers2.size()
<< "\nvector after initialization:";
outputVector(integers2);
// input and print integers1 and integers2
std::cout << "\nEnter 17 integers:\n";
//inputVector(integers1);
//inputVector(integers2);
std::cout << "\nAfter input, the vectors contain:\n"
<< "integers1:";
outputVector(integers1);
std::cout << "integers2:";
outputVector(integers2);
// use inequality (!=) operator with vector objects
std::cout << "\nEvaluating: integers1 != integers2\n";
if (integers1 != integers2) {
std::cout << "integers1 and integers2 are not equal\n";
}
// create vector integers3 using integers1 as an
// initializer; print size and contents
std::vector integers3{integers1}; // copy constructor
std::cout << "\nSize of vector integers3 is " << integers3.size()
<< "\nvector after initialization: ";
outputVector(integers3);
// use overloaded assignment (=) operator
std::cout << "\nAssigning integers2 to integers1:\n";
integers1 = integers2; // assign integers2 to integers1
std::cout << "integers1: ";
outputVector(integers1);
std::cout << "integers2: ";
outputVector(integers2);
// use equality (==) operator with vector objects
std::cout << "\nEvaluating: integers1 == integers2\n";
if (integers1 == integers2) {
std::cout << "integers1 and integers2 are equal\n";
}
// use the value at location 5 as an rvalue
std::cout << "\nintegers1.at(5) is " << integers1.at(5);
// use integers1.at(5) as an lvalue
std::cout << "\n\nAssigning 1000 to integers1.at(5)\n";
integers1.at(5) = 1000;
std::cout << "integers1: ";
outputVector(integers1);
// attempt to use out-of-range index
try {
std::cout << "\nAttempt to display integers1.at(15)\n";
std::cout << integers1.at(15) << '\n'; // ERROR: out of range
}
catch (const std::out_of_range& ex) {
std::cerr << "An exception occurred: " << ex.what() << '\n';
}
// changing the size of a vector
std::cout << "\nCurrent integers3 size is: " << integers3.size();
integers3.push_back(1000); // add 1000 to the end of the vector
std::cout << "\nNew integers3 size is: " << integers3.size()
<< "\nintegers3 now contains: ";
outputVector(integers3);
}
// output vector contents
void outputVector(const std::vector<int>& items) {
for (const int& item : items) {
std::cout << item << " ";
}
std::cout << '\n';
}
// input vector contents
void inputVector(std::vector<int>& items) {
for (int& item : items) {
std::cin >> item;
}
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/

View File

@ -0,0 +1,30 @@
// fig07_01.cpp
// Pointer operators & and *.
#include <iostream>
using namespace std;
int main() {
constexpr int a{7}; // initialize a with 7
const int* aPtr{&a}; // initialize aPtr with address of int variable a
cout << "The address of a is " << &a
<< "\nThe value of aPtr is " << aPtr;
cout << "\n\nThe value of a is " << a
<< "\nThe value of *aPtr is " << *aPtr << '\n';
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/

View File

@ -0,0 +1,36 @@
// fig07_02.cpp
// Pass-by-value used to cube a variable's value.
#include <fmt/format.h>
#include <iostream>
int cubeByValue(int n); // prototype
int main() {
int number{5};
std::cout << fmt::format("Original value of number is {}\n", number);
number = cubeByValue(number); // pass number by value to cubeByValue
std::cout << fmt::format("New value of number is {}\n", number);
}
// calculate and return cube of integer argument
int cubeByValue(int n) {
return n * n * n; // cube local variable n and return result
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/

View File

@ -0,0 +1,35 @@
// fig07_03.cpp
// Pass-by-reference with a pointer argument used to cube a
// variable's value.
#include <fmt/format.h>
#include <iostream>
void cubeByReference(int* nPtr); // prototype
int main() {
int number{5};
std::cout << fmt::format("Original value of number is {}\n", number);
cubeByReference(&number); // pass number address to cubeByReference
std::cout << fmt::format("New value of number is {}\n", number);
}
// calculate cube of *nPtr; modifies variable number in main
void cubeByReference(int* nPtr) {
*nPtr = *nPtr * *nPtr * *nPtr; // cube *nPtr
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/

View File

@ -0,0 +1,49 @@
// fig07_06.cpp
// C++20: Creating std::arrays with to_array.
#include <fmt/format.h>
#include <iostream>
#include <array>
int main() {
// generic lambda to display a collection of items
const auto display{
[](const auto& items) {
for (const auto& item : items) {
std::cout << fmt::format("{} ", item);
}
}
};
const int values1[]{10, 20, 30};
// creating a std::array from a built-in array
const auto array1{std::to_array(values1)};
std::cout << fmt::format("array1.size() = {}\n", array1.size())
<< "array1: ";
display(array1); // use lambda to display contents
// creating a std::array from an initializer list
const auto array2{std::to_array({1, 2, 3, 4})};
std::cout << fmt::format("\n\narray2.size() = {}\n", array2.size())
<< "array2: ";
display(array2); // use lambda to display contents
std::cout << '\n';
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/

View File

@ -0,0 +1,26 @@
// fig07_07.cpp
// Attempting to modify data through a
// nonconstant pointer to constant data.
int main() {
int y{0};
const int* yPtr{&y};
*yPtr = 100; // error: cannot modify a const object
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/

View File

@ -0,0 +1,29 @@
// fig07_08.cpp
// Attempting to modify a constant pointer to nonconstant data.
int main() {
int x, y;
// ptr is a constant pointer to an integer that can be modified
// through ptr, but ptr always points to the same memory location.
int* const ptr{&x}; // const pointer must be initialized
*ptr = 7; // allowed: *ptr is not const
ptr = &y; // error: ptr is const; cannot assign to it a new address
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/

View File

@ -0,0 +1,35 @@
// fig07_09.cpp
// Attempting to modify a constant pointer to constant data.
#include <iostream>
using namespace std;
int main() {
int x{5}, y;
// ptr is a constant pointer to a constant integer.
// ptr always points to the same location; the integer
// at that location cannot be modified.
const int* const ptr{&x};
cout << *ptr << endl;
*ptr = 7; // error: *ptr is const; cannot assign new value
ptr = &y; // error: ptr is const; cannot assign new address
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/

View File

@ -0,0 +1,39 @@
// fig07_10.cpp
// Sizeof operator when used on a built-in array's name
// returns the number of bytes in the built-in array.
#include <fmt/format.h>
#include <iostream>
size_t getSize(double* ptr); // prototype
int main() {
double numbers[20]; // 20 doubles; occupies 160 bytes on our system
std::cout << fmt::format("Number of bytes in numbers is {}\n\n",
sizeof(numbers));
std::cout << fmt::format("Number of bytes returned by getSize is {}\n",
getSize(numbers));
}
// return size of ptr
size_t getSize(double* ptr) {
return sizeof(ptr);
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/

View File

@ -0,0 +1,51 @@
// fig07_11.cpp
// sizeof operator used to determine standard data type sizes.
#include <fmt/format.h>
#include <iostream>
int main() {
constexpr char c{}; // variable of type char
constexpr short s{}; // variable of type short
constexpr int i{}; // variable of type int
constexpr long l{}; // variable of type long
constexpr long long ll{}; // variable of type long long
constexpr float f{}; // variable of type float
constexpr double d{}; // variable of type double
constexpr long double ld{}; // variable of type long double
constexpr int array[20]{}; // built-in array of int
const int* const ptr{array}; // variable of type int*
std::cout << fmt::format("sizeof c = {}\tsizeof(char) = {}\n",
sizeof c, sizeof(char));
std::cout << fmt::format("sizeof s = {}\tsizeof(short) = {}\n",
sizeof s, sizeof(short));
std::cout << fmt::format("sizeof i = {}\tsizeof(int) = {}\n",
sizeof i, sizeof(int));
std::cout << fmt::format("sizeof l = {}\tsizeof(long) = {}\n",
sizeof l, sizeof(long));
std::cout << fmt::format("sizeof ll = {}\tsizeof(long long) = {}\n",
sizeof ll, sizeof(long long));
std::cout << fmt::format("sizeof f = {}\tsizeof(float) = {}\n",
sizeof f, sizeof(float));
std::cout << fmt::format("sizeof d = {}\tsizeof(double) = {}\n",
sizeof d, sizeof(double));
std::cout << fmt::format("sizeof ld = {}\tsizeof(long double) = {}\n",
sizeof ld, sizeof(long double));
std::cout << fmt::format("sizeof array = {}\n", sizeof array);
std::cout << fmt::format("sizeof ptr = {}\n", sizeof ptr);
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/

View File

@ -0,0 +1,100 @@
// fig07_12.cpp
// C++20 spans: Creating views into containers.
#include <array>
#include <fmt/format.h>
#include <iostream>
#include <numeric>
#include <span>
#include <vector>
// items parameter is treated as a const int* so we also need the size to
// know how to iterate over items with counter-controlled iteration
void displayArray(const int items[], size_t size) {
for (size_t i{0}; i < size; ++i) {
std::cout << fmt::format("{} ", items[i]);
}
}
// span parameter contains both the location of the first item
// and the number of elements, so we can iterate using range-based for
void displaySpan(std::span<const int> items) {
for (const auto& item : items) { // spans are iterable
std::cout << fmt::format("{} ", item);
}
}
// spans can be used to modify elements in the original data structure
void times2(std::span<int> items) {
for (int& item : items) {
item *= 2;
}
}
int main() {
int values1[]{1, 2, 3, 4, 5};
std::array values2{6, 7, 8, 9, 10};
std::vector values3{11, 12, 13, 14, 15};
// must specify size because the compiler treats displayArray's items
// parameter as a pointer to the first element of the argument
std::cout << "values1 via displayArray: ";
displayArray(values1, 5);
// compiler knows values1's size and automatically creates a span
// representing &values1[0] and the array's length
std::cout << "\nvalues1 via displaySpan: ";
displaySpan(values1);
// compiler also can create spans from std::arrays and std::vectors
std::cout << "\nvalues2 via displaySpan: ";
displaySpan(values2);
std::cout << "\nvalues3 via displaySpan: ";
displaySpan(values3);
// changing a span's contents modifies the original data
times2(values1);
std::cout << "\n\nvalues1 after times2 modifies its span argument: ";
displaySpan(values1);
// spans have various array-and-vector-like capabilities
std::span mySpan{values1}; // span<int>
std::cout << "\n\nmySpan's first element: " << mySpan.front()
<< "\nmySpan's last element: " << mySpan.back();
// spans can be used with standard library algorithms
std::cout << "\n\nSum of mySpan's elements: "
<< std::accumulate(std::begin(mySpan), std::end(mySpan), 0);
// spans can be used to create subviews of a container
std::cout << "\n\nFirst three elements of mySpan: ";
displaySpan(mySpan.first(3));
std::cout << "\nLast three elements of mySpan: ";
displaySpan(mySpan.last(3));
std::cout << "\nMiddle three elements of mySpan: ";
displaySpan(mySpan.subspan(1, 3));
// changing a subview's contents modifies the original data
times2(mySpan.subspan(1, 3));
std::cout << "\n\nvalues1 after modifying elements via span: ";
displaySpan(values1);
// access a span element via []
std::cout << "\n\nThe element at index 2 is: " << mySpan[2];
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/

View File

@ -0,0 +1,29 @@
// fig07_13.cpp
// Reading in command-line arguments.
#include <fmt/format.h>
#include <iostream>
int main(int argc, char* argv[]) {
std::cout << fmt::format("Number of arguments: {}\n\n", argc);
for (int i{0}; i < argc; ++i) {
std::cout << fmt::format("{}\n", argv[i]);
}
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/

View File

@ -0,0 +1,48 @@
// fig07_14.cpp
// C++20: Creating std::arrays from string literals with to_array.
#include <fmt/format.h>
#include <iostream>
#include <array>
int main() {
// lambda to display a collection of items
const auto display{
[](const auto& items) {
for (const auto& item : items) {
std::cout << fmt::format("{} ", item);
}
}
};
// initializing an array with a string literal
// creates a one-element array<const char*>
const auto array1{std::array{"abc"}};
std::cout << fmt::format("array1.size() = {}\narray1: ",
array1.size());
display(array1); // use lambda to display contents
// creating std::array of characters from a string literal
const auto array2{std::to_array("C++20")};
std::cout << fmt::format("\n\narray2.size() = {}\narray2: ",
array2.size());
display(array2); // use lambda to display contents
std::cout << '\n';
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/

View File

@ -0,0 +1,6 @@
account,name,balance
100,Jones,24.98
200,Doe,345.67
300,White,0.0
400,Stone,-42.16
500,Rich,224.62
1 account name balance
2 100 Jones 24.98
3 200 Doe 345.67
4 300 White 0.0
5 400 Stone -42.16
6 500 Rich 224.62

View File

@ -0,0 +1,47 @@
// fig08_01.cpp
// Demonstrating string assignment and concatenation.
#include <fmt/format.h>
#include <iostream>
#include <string>
int main() {
std::string s1{"cat"};
std::string s2; // initialized to the empty string
std::string s3; // initialized to the empty string
s2 = s1; // assign s1 to s2
s3.assign(s1); // assign s1 to s3
std::cout << fmt::format("s1: {}\ns2: {}\ns3: {}\n\n", s1, s2, s3);
s2.at(0) = 'r'; // modify s2
s3.at(2) = 'r'; // modify s3
std::cout << fmt::format("After changes:\ns2: {}\ns3: {}", s2, s3);
std::cout << "\n\nAfter concatenations:\n";
std::string s4{s1 + "apult"}; // concatenation
s1.append("acomb"); // create "catacomb"
s3 += "pet"; // create "carpet" with overloaded +=
std::cout << fmt::format("s1: {}\ns3: {}\ns4: {}\n", s1, s3, s4);
// append locations 4 through end of s1 to
// create string "comb" (s5 was initially empty)
std::string s5; // initialized to the empty string
s5.append(s1, 4, s1.size() - 4);
std::cout << fmt::format("s5: {}", s5);
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/

View File

@ -0,0 +1,62 @@
// fig08_02.cpp
// Comparing strings.
#include <fmt/format.h>
#include <iostream>
#include <string>
void displayResult(const std::string& s, int result) {
if (result == 0) {
std::cout << fmt::format("{} == 0\n", s);
}
else if (result > 0) {
std::cout << fmt::format("{} > 0\n", s);
}
else { // result < 0
std::cout << fmt::format("{} < 0\n", s);
}
}
int main() {
const std::string s1{"Testing the comparison functions."};
const std::string s2{"Hello"};
const std::string s3{"stinger"};
const std::string s4{s2}; // "Hello"
std::cout << fmt::format("s1: {}\ns2: {}\ns3: {}\ns4: {}",
s1, s2, s3, s4);
// comparing s1 and s4
if (s1 > s4) {
std::cout << "\n\ns1 > s4\n";
}
// comparing s1 and s2
displayResult("s1.compare(s2)", s1.compare(s2));
// comparing s1 (elements 2-6) and s3 (elements 0-4)
displayResult("s1.compare(2, 5, s3, 0, 5)",
s1.compare(2, 5, s3, 0, 5));
// comparing s2 and s4
displayResult("s4.compare(0, s2.size(), s2)",
s4.compare(0, s2.size(), s2));
// comparing s2 and s4
displayResult("s2.compare(0, 3, s4)", s2.compare(0, 3, s4));
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/

View File

@ -0,0 +1,27 @@
// fig08_03.cpp
// Demonstrating string member function substr.
#include <iostream>
#include <string>
int main() {
const std::string s{"airplane"};
std::cout << s.substr(3, 4) << '\n'; // retrieve substring "plan"
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/

View File

@ -0,0 +1,29 @@
// fig08_04.cpp
// Using the swap function to swap two strings.
#include <fmt/format.h>
#include <iostream>
#include <string>
int main() {
std::string s1{"one"};
std::string s2{"two"};
std::cout << fmt::format("Before swap:\ns1: {}; s2: {}", s1, s2);
s1.swap(s2); // swap strings
std::cout << fmt::format("\n\nAfter swap:\ns1: {}; s2: {}", s1, s2);
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/

View File

@ -0,0 +1,57 @@
// fig08_05.cpp
// Printing string characteristics.
#include <fmt/format.h>
#include <iostream>
#include <string>
// display string statistics
void printStatistics(const std::string& s) {
std::cout << fmt::format(
"capacity: {}\nmax size: {}\nsize: {}\nempty: {}",
s.capacity(), s.max_size(), s.size(), s.empty());
}
int main() {
std::string string1; // empty string
std::cout << "Statistics before input:\n";
printStatistics(string1);
std::cout << "\n\nEnter a string: ";
std::cin >> string1; // delimited by whitespace
std::cout << fmt::format("The string entered was: {}\n", string1);
std::cout << "Statistics after input:\n";
printStatistics(string1);
std::cout << "\n\nEnter a string: ";
std::cin >> string1; // delimited by whitespace
std::cout << fmt::format("The string entered was: {}\n", string1);
std::cout << "Statistics after input:\n";
printStatistics(string1);
// append 46 characters to string1
string1 += "1234567890abcdefghijklmnopqrstuvwxyz1234567890";
std::cout << fmt::format("\n\nstring1 is now: {}\n", string1);
std::cout << "Statistics after concatenation:\n";
printStatistics(string1);
string1.resize(string1.size() + 10); // add 10 elements to string1
std::cout << "\n\nStatistics after resizing to add 10 characters:\n";
printStatistics(string1);
std::cout << '\n';
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/

View File

@ -0,0 +1,59 @@
// fig08_06.cpp
// Demonstrating the string find member functions.
#include <fmt/format.h>
#include <iostream>
#include <string>
int main() {
const std::string s{"noon is 12pm; midnight is not"};
std::cout << "Original string: " << s;
// find "is" from the beginning and end of s
std::cout << fmt::format("\ns.find(\"is\"): {}\ns.rfind(\"is\"): {}",
s.find("is"), s.rfind("is"));
// find 'o' from beginning
int location{s.find_first_of("misop")};
std::cout << fmt::format("\ns.find_first_of(\"misop\") found {} at {}",
s.at(location), location);
// find 'o' from end
location = s.find_last_of("misop");
std::cout << fmt::format("\ns.find_last_of(\"misop\") found {} at {}",
s.at(location), location);
// find '1' from beginning
location = s.find_first_not_of("noi spm");
std::cout << fmt::format(
"\ns.find_first_not_of(\"noi spm\") found {} at {}",
s.at(location), location);
// find ';' at location 12
location = s.find_first_not_of("12noi spm");
std::cout << fmt::format(
"\ns.find_first_not_of(\"12noi spm\") found {} at {}",
s.at(location), location);
// search for characters not in "noon is 12pm; midnight is not"
location = s.find_first_not_of("noon is 12pm; midnight is not");
std::cout << fmt::format("\n{}: {}\n",
"s.find_first_not_of(\"noon is 12pm; midnight is not\")",
location);
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/

View File

@ -0,0 +1,58 @@
// fig08_07.cpp
// Demonstrating string member functions erase and replace.
#include <fmt/format.h>
#include <iostream>
#include <string>
int main() {
// compiler concatenates all parts into one string
std::string string1{"The values in any left subtree"
"\nare less than the value in the"
"\nparent node and the values in"
"\nany right subtree are greater"
"\nthan the value in the parent node"};
std::cout << fmt::format("Original string:\n{}\n\n", string1);
string1.erase(62); // remove from index 62 through end of string1
std::cout << fmt::format("string1 after erase:\n{}\n\n", string1);
size_t position{string1.find(" ")}; // find first space
// replace all spaces with period
while (position != std::string::npos) {
string1.replace(position, 1, ".");
position = string1.find(" ", position + 1);
}
std::cout << fmt::format("After first replacement:\n{}\n\n", string1);
position = string1.find("."); // find first period
// replace all periods with two semicolons
// NOTE: this will overwrite characters
while (position != std::string::npos) {
string1.replace(position, 2, "xxxxx;;yyy", 5, 2);
position = string1.find(".", position + 2);
}
std::cout << fmt::format("After second replacement:\n{}\n", string1);
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/

View File

@ -0,0 +1,35 @@
// fig08_08.cpp
// Demonstrating std::string insert member functions.
#include <fmt/format.h>
#include <iostream>
#include <string>
int main() {
std::string s1{"beginning end"};
std::string s2{"12345678"};
std::cout << fmt::format("Initial strings:\ns1: {}\ns2: {}\n\n",
s1, s2);
s1.insert(10, "middle "); // insert "middle " at location 10
s2.insert(3, "xx", 0, std::string::npos); // insert "xx" at location 3
std::cout << fmt::format("Strings after insert:\ns1: {}\ns2: {}\n",
s1, s2);
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/

View File

@ -0,0 +1,55 @@
// fig08_09.cpp
// C++17 string_view.
#include <fmt/format.h>
#include <iostream>
#include <string>
#include <string_view>
int main() {
std::string s1{"red"};
std::string s2{s1};
std::string_view v1{s1}; // v1 "sees" the contents of s1
std::cout << fmt::format("s1: {}\ns2: {}\nv1: {}\n\n", s1, s2, v1);
// string_views see changes to the characters they view
s1.at(0) = 'R'; // capitalize s1
std::cout << fmt::format("s1: {}\ns2: {}\nv1: {}\n\n", s1, s2, v1);
// string_views are comparable with strings or string_views
std::cout << fmt::format("s1 == v1: {}\ns2 == v1: {}\n\n",
s1 == v1, s2 == v1);
// string_view can remove a prefix or suffix
v1.remove_prefix(1); // remove one character from the front
v1.remove_suffix(1); // remove one character from the back
std::cout << fmt::format("s1: {}\nv1: {}\n\n", s1, v1);
// string_views are iterable
std::string_view v2{"C-string"};
std::cout << "The characters in v2 are: ";
for (char c : v2) {
std::cout << c << " ";
}
// string_views enable various string operations on C-Strings
std::cout << fmt::format("\n\nv2.size(): {}\n", v2.size());
std::cout << fmt::format("v2.find('-'): {}\n", v2.find('-'));
std::cout << fmt::format("v2.starts_with('C'): {}\n",
v2.starts_with('C'));
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/

View File

@ -0,0 +1,45 @@
// fig08_10.cpp
// Creating a sequential file.
#include <cstdlib> // exit function prototype
#include <fmt/format.h>
#include <fstream> // contains file stream processing types
#include <iostream>
#include <string>
int main() {
// ofstream opens the file
if (std::ofstream output{"clients.txt", std::ios::out}) {
std::cout << "Enter the account, name, and balance.\n"
<< "Enter end-of-file to end input.\n? ";
int account;
std::string name;
double balance;
// read account, name and balance from cin, then place in file
while (std::cin >> account >> name >> balance) {
output << fmt::format("{} {} {}\n", account, name, balance);
std::cout << "? ";
}
}
else {
std::cerr << "File could not be opened\n";
std::exit(EXIT_FAILURE);
}
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/

View File

@ -0,0 +1,46 @@
// fig08_11.cpp
// Reading and printing a sequential file.
#include <cstdlib>
#include <fmt/format.h>
#include <fstream> // file stream
#include <iostream>
#include <string>
int main() {
// ifstream opens the file
if (std::ifstream input{"clients.txt", std::ios::in}) {
std::cout << fmt::format("{:<10}{:<13}{:>7}\n",
"Account", "Name", "Balance");
int account;
std::string name;
double balance;
// display each record in file
while (input >> account >> name >> balance) {
std::cout << fmt::format("{:<10}{:<13}{:>7.2f}\n",
account, name, balance);
}
}
else {
std::cerr << "File could not be opened\n";
std::exit(EXIT_FAILURE);
}
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/

View File

@ -0,0 +1,44 @@
// fig08_12.cpp
// Using an ostringstream object.
#include <iostream>
#include <sstream> // header for string stream processing
#include <string>
int main() {
std::ostringstream output; // create ostringstream object
const std::string string1{"Output of several data types "};
const std::string string2{"to an ostringstream object:"};
const std::string string3{"\ndouble: "};
const std::string string4{"\n int: "};
constexpr double d{123.4567};
constexpr int i{22};
// output strings, double and int to ostringstream
output << string1 << string2 << string3 << d << string4 << i;
// call str to obtain string contents of the ostringstream
std::cout << "output contains:\n" << output.str();
// add additional characters and call str to output string
output << "\nmore characters added";
std::cout << "\n\noutput now contains:\n" << output.str() << '\n';
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/

View File

@ -0,0 +1,45 @@
// fig08_13.cpp
// Demonstrating input from an istringstream object.
#include <fmt/format.h>
#include <iostream>
#include <sstream>
#include <string>
int main() {
const std::string inputString{"Amanda test 123 4.7 A"};
std::istringstream input{inputString};
std::string s1;
std::string s2;
int i;
double d;
char c;
input >> s1 >> s2 >> i >> d >> c;
std::cout << "Items extracted from the istringstream object:\n"
<< fmt::format("{}\n{}\n{}\n{}\n{}\n", s1, s2, i, d, c);
// attempt to read from empty stream
if (long value; input >> value) {
std::cout << fmt::format("\nlong value is: {}\n", value);
}
else {
std::cout << fmt::format("\ninput is empty\n");
}
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/

Some files were not shown because too many files have changed in this diff Show More