C++ std::string::empty
Check whether an optional text field contains zero characters.
A simple example
std::string::empty
- Start with ""
- Do this Check whether any characters exist
- Result Empty
#include <iostream>
#include <string>
int main() {
const std::string value = "";
std::cout << ((value.empty()) ? "yes" : "no") << "\n";
return 0;
}
yes
Syntax
value.empty()
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 for an untouched delivery note
A form can look blank even when its field contains a space. Examine the stored input before marking the answer as missing, because an empty string and whitespace can require separate checks.
#include <iostream>
#include <string>
int main() {
const std::string value = "";
std::cout << ((value.empty()) ? "yes" : "no") << "\n";
return 0;
}
yes
A new empty field contains no text.
Check a student answer containing one space
An examination form receives a response consisting of a single space. Determine whether the raw field is empty before deciding whether the student has supplied a meaningful answer.
#include <iostream>
#include <string>
int main() {
const std::string value = " ";
std::cout << ((value.empty()) ? "yes" : "no") << "\n";
return 0;
}
no
Even a single space makes the string nonempty.
Accept a written handover
A night worker types a short handover message. The clerk first checks whether the field contains any characters at all. Is the supplied field empty?
What to watch for
A space is still a character. Use a whitespace check if a spaces-only entry should be rejected.