nullで終了する文字列のサイズを取得する方法はありますか?
元。
char* buffer = "an example";
unsigned int buffer_size; // I want to get the size of 'buffer'
nullで終了する文字列のサイズを取得する方法はありますか?
元。
char* buffer = "an example";
unsigned int buffer_size; // I want to get the size of 'buffer'
C ++ 11では、文字列リテラルの型const char[]
がであり、への変換char*
(つまり、non-へのポインタconst
)は不正であることに注意してください。これは言った:
#include <cstring> // You will need this for strlen()
#include <iostream>
int main()
{
char const* buffer = "an example";
// ^^^^^
std::cout << std::strlen(buffer);
}
ただし、CではなくC ++を記述しているため(少なくともこれはタグが主張していることです)、C++標準ライブラリのクラスとアルゴリズムを使用する必要があります。
#include <string> // You will need this for std::string
#include <iostream>
int main()
{
std::string buffer = "an example";
std::cout << buffer.length();
}
実例を参照してください。
ノート:
C文字列を必要とするAPIを使用している場合はc_str()
、オブジェクトのメンバー関数を使用std::string
してポインタを取得char const*
できます。これを含むstd :: stringオブジェクトメモリバッファのc_str()メンバー関数を使用できます。カプセル化されたC文字列。そのバッファの内容を変更できないという事実に注意してください。
std::string s = "Hello World!";
char const* cstr = s.c_str();
strlen(buffer)
からお試しください<cstring>
。渡した文字列の長さを返します。