I. The Standard Library and # Include
1. C++ standard library
(1) To use part of the standard library, use the #include directive.
Ex) if you would like to use cout and cin in the code, you’ll need to include <iostream> library at the top of your .cpp file
#include <iostream>
using namespace std;
(3) The using namespace std; directive is generally used with included libraries, we can use shorthand names like cout and cin. Without it, we need to write out std::cout and std::cin. The using namespace std; line implicitly puts the std:: on everything so you don’t have to.
<cmath> | standard math library Ex) sqrt(), pow(), sin()… |
<cstdlib> | common functions Ex) rand() |
<iostream> | standard terminal input/output Ex) cin, cout |
<fstream> | file input/output through streams |
<iomanip> | configure the way output is printed Ex) floating point precision |
<string> | The string datatype and associated functionality |
<vector> | <vector> The vector datatype (a container) |
II. Introduction to Strings
The string datatype represents a sequence of text characters – perhaps a single word, a whole sentence, or even a full document of text, since spaces and newlines can be represented as special characters.
1. Strings and the string library
(1) A string is basically a sequence of characters.
(2) To use string variables or any of the built-in string functions, first include the string library.
2. String literals
String literals are basically hardcoded strings, which are specified by a sequence of characters in double quotes “.
3. Concatenation
Concatenation: the process of appending two strings together, one after the other.
(1) In C++, the + operator performs concatenation.
(2) In C++, the +- updated a variable by concatenating an additional string onto it.
4. string Comparison
(1) The string datatype supports the regular relational operators, based on a lexicographic (alphabetic) ordering.
==, !=, <, <=, >, >=
(2) The first differing character determines the result.
(3) EX) the following comparisons all yield true:
5. string Representation
(1) Internally, the string datatype is fairly complex.
(2) However, for our purposes, it suffices to think of it as a sequence of values of the char datatype.
5. char Representation
(1) In memory, chars are usually stored as numbers.
(2) The number used to represent each character is determined by its ASCII code (a number 0-255):
6. Implicit conversions with char
(1) The numeric ASCII code is used whenever a char is implicitly converted to an int.
(2) It is easy to write code that looks like it does one thing, but actually does something else:
7. Special characters
(1) Other ASCII codes are used to represent non-printable characters with special meanings:
EX) A tab character has ASCII code 9
EX) A newline character has ASCII code 10
(2) But how can we use these special characters? We can’t exactly type them into our code as literals.
(3) Some special characters would interfere with the syntax of our program.
(4) Instead, we can use an escape sequence to specify these special characters in string or character literals.
- Generally, escape sequences start with the \ (backslash) character. The compiler considers the whole escape sequence as a single character.
8. The length and size functions
(1) To get the number of characters in a string, use either the length function or the size function.
(2) Use the . operator to apply these functions to a particular string.
To use strings in a C++, make sure to the line #include <string> at the top of your source file, and create variables with the string datatype. As usual, using namespace std; makes things more convenient.
Strings can be initialized with a particular value by using a string literal with double quotes, “hello”, or can be left alone and they will default-initialize to an empty string “”.
9. Operators and functions
s1 + s2 | Concatenate the two strings together (does not change original s1 or s2) |
s1 += s2 | Update the value of s1 by adding the characters in s2. Equivalent to s1 = s1 + s2 |
s1 == s2 | Checks whether the two strings represent the same text. They don’t have to be literally the same variables in memory. != work similarly. |
s1 < s2 | Compares the two strings lexicographically. Returns true if s1 would be listed before s1. Ex) “apple” is less than “banana”, “banana” is less than “bananas”. <=, >, >= work similarly. |
str.size() or str.length() |
Functions that return the number of characters in the string. This does include “whitespace” characters like spaces or newlines. |
* If both of the operands you are using are string literals, like “hello” + “world” or “cat” < “bat”, it won’t work correctly. ( This is because internally string literals aren’t real string – but as long as you have at least one actual string variable, the string literal will be converted to match and it will work. (variable 설정을 해야 된다는 것임)
EXERCISE) Repeating String
Write a function called repeat that repeats a given string a certain number of times and returns the result. For example, if we repeated the string “mouse” five times, the resulting string would be “mousemousemousemousemouse”. (don’t output anything in the function; just return the repeated string.)
III. String Indexing (#include <string>)
1. String indexing
(1) Just as in MATLAB, we can use indexing in C++ to access individual elements of a sequence like a string.
(2) Two key differences:
-> Indexing in C++ uses the square brackets []. (rather than parentheses)
-> Indices start a 0 rather than 1.
2. Indexing out of bounds
(1) C++ will gladly let you index out of bounds.
-> There’s no immediate error like we would get in MATLAB.
(2) This can lead to very weird behavior.
(3) Instead of using [] indexing, you can use .at() to index into a string. Using the function warns you if you are about to go out-of-bounds but is a little bit slower.
* 곧, 부여된 index 숫자가 없을 시, 해당 index 는 바꾸는 것 / 추가 되는 것이 불가능하다.
3. Indexing with the at function
(1) You can also use the at function to index into a string.
-> The advantage of at is that it checks whether the provided index is within bounds and if not, causes an error immediately.
IV. More String Operations
1. .empty()
The empty function tells you whether a string is the empty string (“”) or not.
2. .find()
The find function searches a string for the first occurrence of a second string.
This code finds the first occurrence of “victors” in the string “Hail to the victors valiant”;
The find function returns the index where the first occurrence of a second string is located. If the second string is not in the first string, find will return string::npos.
EX) What will the value of index be after the following code runs?
A: 8
- “the” begins at index 8.
3. .replace()
The replace function takes three arguments: an integer pos, an integer len, and a string str2.
The replace function replaces the portion of the string that begins at character pos and spans len characters by new contents str2.
To replace the portion of chant that begins at 0 and spans 4 characters, we replaced it with a new string: “HAIL”.
* len does not need to be the same length as str2.
EX) What will the following code output?
A: Hail to the wolverines valiant.
EX) What will the following code output?
A: Hailthe victors valiant.
EX) If you want to replace all of the characters until the end of the string, what should the len parameter be?
A: string::npos
- String::npos indicates all characters until the end of the string.
4. .erase()
The erase function takes two arguments: an integer pos and an integer len. The erase function goes into the string at index pos and removes len characters.
5. .substr()
The substr function creates a new string from a substring of another string. It takes two parameters: pos and len. It returns a new substring starting at character pos and going len characters.
(비디오에서 trim 과 같음. Pos, len 부분을 제외하고 나머지가 다 잘림)
EX) what is the value of newString after the following code runs?
A: vict
V. User Input and Output (#include <iostream>)
1. Introduction to User Input/Output
(1) Output: cout print output to the console. Printing out endl prints out a new line.
(2) cin gets input from the user. When you use cin, the program will block until the user inputs something. The user input will go into a buffer, a holding place for data until it is processed and used.
* A real program will process any pending cin expressions immediately once you type some input and press enter at the terminal.
IV. Data Types and Cin
When using cin to get input from the user, we need to make sure the type of the variable we’re reading into is appropriate for the type of input we expect them to enter.
We can use cin to read in both characters and strings. The getline function can be used to read an entire line of input into a string variable:
IIV. Common Pattern
1. Validating Input
Sometimes we’d like to verify that the user actually entered reasonable input.
We can do this with iteration – basically, set up a loop that keeps asking them until they give us something that meets our criteria. (값 찾으면 while 멈춤)
double x; while(cin >> x && /* some condition on x is not net */){ cout << “Try again” << endl; } |
EX) Requiring the user to enter a positive number.
This goes beyond the type of the input and has to do with the value they enter:
2. Detecting a Sentinel
We want to read input from the user until they tell us to stop. To do this, we’ll look for a special input called a sentinel. (while 멈추는 지뢰 설정, done 아니고 숫자나 다른 것도 됨.)
(Here, our sentinel value is “done”)
string x; while(cin >> x && x !=”done”){ // do something with x } |
EX) A simple calculator program that asks the user to enter some numbers to add. The program will keep accepting numbers until they enter the sentinel value.
(1)
(2)
(3)
EXERCISE) Annoying Echo Program
“The annoying echo program”. It continuously accepts input from a user via cin and then immediately echos that word back to them through cout. (this program reads word-by-word, and not line-by-line, so you should not use the getline function.) However, if you enter “STOP” (in all capital letters), the program will stop.
Example of output/input ($ indicates user input lines)
=============================
$ Hi
Hi
$ How are you
How
are
you
$ Stop
Stop
$ STOP
Ok fine I’ll stop :(
=============================
IIV. File Input / Output with Streams
1. Files
(1) It is easiest to work with files in the same directory where you run the program.
(2) just provide the name of the file.
filename.txt
data.in
server_errors.log
File extension: the part after the file name. It’s not required, but it usually provides some information about what the file is used for.
2. File streams
(1) To use file streams, first we need the fstream library:
#include <fstream>
(2) For convenience, you’ll also want the standard namespace:
using namespace std;
(3) To write output to a file, you use an ofstream object.
ofstream fout(“myFile.txt”); fout << “Something to write to the file” << endl; fout.close(); |
(4) To read input from a file, you use an ifstream object.
ifstream fin(“myFile.txt”); string word; fin >> word; fin.close(); |
(5) To check that a file opened correctly, use fin.is_open(). If the file did not open correctly, you can return 1; in the main() function. This exits the program, and acts as an “exit code”, telling the person who ran the code that something went wrong.
3. File output with ofstream
(1) Create an ofstream:
- This creates an ofstream object named fout.
- This ofstream will send output to a file named “greet.out”.
- If the file doesn’t exist already, it will be created.
- If the file already exists, it will be overwritten.
(2) Then, write to the file using the ofstream and <<
Ex) File output
A program that creates a file containing the numbers 0 through 4 on separate lines:
4. File input with ifstream
(1) Create an ifstream:
- This creates an ifstream object named fin.
- This ifstream will read input from a file named “words.in”.
- If the file doesn’t exist, there could be problems. Make sure the file is open.
(2) Then, read from the file using the ifstream and >>
Ex) File input
5. Checking for Errors when Opening a File
(1) Sometimes, the program is unable to open a file for input.
-> It doesn’t exist
-> A different program is using it
-> Your program doesn’t have permission to use it
(2) Check whether the file was opened successfully using the .is_open() function, which is applied to the ifstream:
fin.is_open()
- Fin is the ifstream object
- The dot applies is_open to fin, specifically.
- Call the is_open function, which returns a bool.
Ex) File input
- When the file is not open.
- When the file is open.
IV. Common Pattern : Reading Until the End
In a previous example, we hardcoded the number of iterations for the input loop.
What if we don’t know this ahead of time?
* Strategy: Put the read operation in the condition of your loop. It will yield false if you runt out of input.
If we don’t know the size of a file ahead of time, we can use a loop to keep reading the file in until we reach the end:
ifstream fin(“myFile.txt”); string word; while (fin >> word){ //do something with the word } fin.close(); |
In the previous example, we used a loop to read individual words from a file until we reached the end of the file. Similarly, we can read entire lines (using getline) from a file until we reach the end of the file.
ifstream fin(“myFile.txt”); string line; while (getline(fin,line)){ //do something with the line } fin.close(); |
V. Common Pattern: Reading In Multiple Pieces of Data
Let’s suppose we have the following file with information about various world cities. Each line of the file contains three pieces of information: the city name, the average temperature of the city (in Fahrenheit), and the population of the city.
Algiers 63.3 3915811
Baghdad 72.99 8126755
Taipei 73.4 2646204
…
Wichita 57.0 391352
We want to read this data in our program. We want to put the city name in a string variable, the temperature in a double, and the population in an int.
The loop will keep iterating until we reach the end of the file. Each time through the loop, we will read in three variables – cityName, avgTemp, and pop.
EXERCISE) Website Data
In order to better optimize the website layout. You have a data file website_traffic.dat that looks like this:
====================================
113.1.60.173 10:59am 100 2
141.234.110.240 11:34pm 800 20
77.191.52.132 7:02pm 600 3
118.170.76.10 6:00am 200 0
====================================
Each line in the file contains data about one unique visitor to your website. Each line contains the following four pieces of information: the IP address of the visitor, the time that they first visited the website, how many seconds they spent on the website, and how many links they clicked on the website.
Arrange the lines of code below to write a program that reads in all of the data from website_traffic.dat and then outputs the data to the terminal. Initialize the fine stream before initializing the variables to hold the data from the file.
EXERCISE) Replace dome
Download the file dome.txt, replaces each occurrence of the word “dome” with “DOME”, and saves the result to a new line dome_new.txt (Words separated by spaces, so just print out each word to your new file separated by a space as well.)
'[Umich] COE Core > ENGR 101 (Matlab, C++)' 카테고리의 다른 글
Umich ENGR 101 Project 4 Overview (Summary) (0) | 2022.12.01 |
---|---|
[Notes] Ch.17 Vectors in C++ (Runestone) (0) | 2022.11.18 |
[Notes] Ch.15 Functions in C++ (Runestone) (0) | 2022.11.18 |
[Notes] Ch.14 Iteration (Runestone) (0) | 2022.11.18 |
[Notes] Ch.13 More C++ Basics and Branching (Runestone) (0) | 2022.11.18 |
댓글