2

次のコードがあるとします。

const int size = 20;
char buffer[size];

// From the Linux man page for snprintf():
//
// The 'res' is the number of bytes that would be written to buffer had size been
// sufficiently large excluding the terminating null byte.  Output bytes beyond
// the size-1st are discarded instead of being written to the buffer, and a null
// byte is written at the end of the bytes actually written into the buffer.
int res = snprintf(buffer, size, "some format with %d and %s", 23, "some string");

if (res >= size) {
  cerr << "The buffer was not large enough, we needed " << res
       << " but only had " << size << "." << endl;
} else {
  cout << "The buffer is big enough, we only needed " << res
       << " but had " << size << "." << endl;
}

これは移植可能ですか? もしそうなら、フェンスポストの状態はすべて正しくなりましたか?

size1 snprintf() への受け渡し

res2以上であることのチェックsize

4

1 に答える 1

1

snprintf は C/C++ 標準の一部ではないため、厳密には移植可能ではありません。Windows には _snprintf がありますが、それ以外は同じです。

フェンスポストの状態はすべて良好です。あなたのprintfは完全にうまくいくわけではありません.equalsの場合は印刷されます

The buffer was not large enough, we needed 215 but only had 215.
于 2011-07-06T20:08:09.517 に答える