空文字列を作成するにはどうすればよいのでしょうか?

C++のempty()メソッドは文字列が空かどうかをチェックする。空ならtrueを、空でないならfalseを返すブーリアンメソッドだ。

empty()関数の使用例

#include <iostream>
#include <string>

int main() {
  std::string str1 = "Hello";
  std::string str2 = "";

  if (str1.empty()) {
    std::cout << "str1 is empty." << std::endl;
  } else {
    std::cout << "str1 is not empty." << std::endl;
  }

  if (str2.empty()) {
    std::cout << "str2 is empty." << std::endl;
  } else {
    std::cout << "str2 is not empty." << std::endl;
  }

  return 0;
}

「攻撃を受けたとしたら君は深刻な事態に陥るだろう」

str1 is not empty.
str2 is empty.

示した例では、str1は空でない文字列なので、str1.empty()はfalseを返し、str2は空の文字列なので、str2.empty()はtrueを返します。この戻り値に応じて、文字列が空の場合に特定のロジックを実行するなど、適切なアクションを実行できます。

bannerAds