std::istream::getline()
要求どおりに文字でいっぱいの配列を読み取るが行末文字ではないかどうかを調べたい場合は、格納されている文字数 (終端の null を差し引いたもの) が抽出された文字と同じかどうかを調べる必要があります。つまり、次の例では、行に 12 文字を超える文字があるかどうかを判断します (13 番目の文字は終端の null に必要です)。
#include <iostream>
#include <string.h>
int main()
{
char array[13];
if (std::cin.getline(array, 13).gcount() == strlen(array)) {
std::cout << "excess characters on the line\n";
}
}
次に余分な文字をストリームから削除したい場合は、次のようなものを使用しますstd::cin.ignore(std::numeric_limits<std::streamsize>::max());
。これも C とタグ付けされているので、C でこれを行う方法はわかりませんが、 に似たものがあることは確かですgcount()
。
実際、仕様を詳しく見ると、文字の読み取り中に改行が発生しない場合にstd::istream:getline()
実際に設定されます(文字が読み取られない場合にも設定されますが、ファイルの終わりに達する前に少なくとも1文字が読み取られた場合は設定されません)。つまり、余分な文字を無視する前にストリームをクリアする必要があり、次の作業を行うことができます。std::ios_base::failbit
std::ios_base:failbit
std::ios_base::failbit
std::ios_base::failbit
std::ios_base::eof()
#include <iostream>
#include <limits>
#include <string.h>
int main()
{
char array[13];
std::cout << "enter password: ";
while (!std::cin.getline(array, 13) && !std::cin.eof())
{
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "password is too long: enter max 12 chars: ";
}
std::cout << "the password is '" << array << "'\n";
}
が設定されているため、ストリームを何かに使用する前std::ios_base::failbit
に呼び出す必要があります。clear()