C++ std::string::size
Count the units in a plain ASCII parcel code before checking its expected length.
A simple example
std::string::size
- Start with "abc"
- Do this Count the characters
- Result 3
#include <iostream>
#include <string>
int main() {
const std::string value = "abc";
std::cout << (value.size()) << "\n";
return 0;
}
3
Syntax
label.size()
Run these examples in C++
Save one example at a time as lesson.cpp. Use C++17 and a Unix-style shell.
c++ -std=c++17 -Wall -Wextra lesson.cpp -o lesson
./lessonCheck the length of a parcel code
A warehouse label uses a compact parcel identifier containing punctuation. Count the stored units across the entire identifier before testing it against the importer's length requirement.
#include <iostream>
#include <string>
int main() {
const std::string label = "PK-407";
std::cout << (label.size()) << "\n";
return 0;
}
6
The two letters, hyphen, and three digits make six units.
Count characters in a train ticket code
A railway prints a prefix, a hyphen and digits as one ticket code. Include the separator when measuring the code so the validation matches the complete printed identifier.
#include <iostream>
#include <string>
int main() {
const std::string value = "T-204";
std::cout << (value.size()) << "\n";
return 0;
}
5
The hyphen is counted along with the letter and digits.
Measure an unused booking code
A registration service checks the length of a short identifier before accepting it. Include every stored unit in the count and consider what the validation sees when no characters were supplied.
#include <iostream>
#include <string>
int main() {
const std::string value = "";
std::cout << (value.size()) << "\n";
return 0;
}
0
An empty code has no units to count.
What to watch for
Byte counts, UTF-16 code units, Unicode code points, and displayed characters can differ outside ASCII.