Operators and std::string
Operators are the symbols you use to combine values: add, compare, decide. You learned them at school, but C++ has its own details that are worth mastering early. In this lesson we review arithmetic, comparison and logical operators, and then we introduce std::string, the type you will use for almost all the text in your programs.
Arithmetic and assignment operators
- + - * / : add, subtract, multiply and divide.
- % : remainder of integer division (integers only).
- += -= *= /= %= : operate and assign at once (x += 2 is x = x + 2).
- ++ and -- : add or subtract one from the variable.
- Parentheses change precedence; * / % are evaluated before + -.
#include <iostream>
int main() {
int a{17};
int b{5};
std::cout << "a + b = " << a + b << '\n';
std::cout << "a / b = " << a / b << '\n'; // 3
std::cout << "a % b = " << a % b << '\n'; // 2
a += 3; // a is now 20
++b; // b is now 6
std::cout << "a = " << a << ", b = " << b << '\n';
bool even = (a % 2 == 0);
bool inRange = (a >= 10) && (a <= 30);
bool either = (a < 0) || (b > 5);
std::cout << std::boolalpha;
std::cout << even << ' ' << inRange << ' ' << either << ' ' << !even << '\n';
return 0;
}Comparison operators (==, !=, <, >, <=, >=) return a bool, and logical operators combine booleans: && (and), || (or) and ! (not). A classic mistake is writing = where you meant ==: if (x = 5) assigns 5 to x and the condition is always true. With -Wall the compiler usually warns you. Also, && and || short-circuit: if the first operand already decides the result, the second is not even evaluated, which helps write safe checks like (n != 0) && (100 / n > 2).
Text with std::string
std::string, defined in the <string> header, is a sequence of characters that grows by itself and copies easily. Forget the C-style char arrays: with std::string you do not manage memory by hand. You concatenate with +, compare with == and <, and it offers member functions: size() gives the length, empty() tells whether it is empty, substr(pos, n) extracts a piece, find(text) returns the position of the first occurrence or std::string::npos if there is none, and push_back or += append at the end. Each character is accessed with s[i], counting from zero.
#include <iostream>
#include <string>
int main() {
std::string first{"Grace"};
std::string last{"Hopper"};
std::string full = first + " " + last;
std::cout << full << " has " << full.size() << " characters\n";
std::cout << "first letter: " << full[0] << '\n';
std::cout << "last name: " << full.substr(6) << '\n';
auto pos = full.find("Hop");
if (pos != std::string::npos) {
std::cout << "found at index " << pos << '\n';
}
full += "!";
std::cout << full << '\n';
std::cout << std::boolalpha << (first == "Grace") << '\n';
return 0;
}A common trap: "abc" + "def" does not compile, because quoted literals are pointers to char, not std::string, and cannot be added. It is enough for one side to be a std::string: std::string{"abc"} + "def" works. Another: size() returns an unsigned type (std::size_t); if you compare it with a negative int you get confusing results, and the compiler warns with -Wall.
One more detail about strings: literals in double quotes, like "hello", are C-style character arrays, not std::string. That is why "he" + "llo" does not compile: you cannot add two literals. The fix is to convert at least one to std::string, for example std::string{"he"} + "llo". And remember that the == operator compares the contents of two std::string objects, not their addresses, so it is safe to use.
✎ Мои заметки
Сохранено только в этом браузере. Войдите, чтобы хранить в аккаунте.0/5000 символов