入力の問題に関して提供したリンクは少し異なります。ユーザーが特定の値を入力することを期待しているが、他の何かが入力されたために値を読み取れない場合があります (整数としましょう)。その場合、getline
入力の行全体を取得してから値を解析するために使用するとよいでしょう。
あなたの場合、あなたはただ言葉を求めています。ストリームから文字列を読み取ると、連続するすべての非空白文字が得られます。そして、句読点を少し無視して、それを「単語」と呼ぶことができます。「無効な入力」について話すとき、私はあなたが何を意味するのかわかりません。ループは、ストリームに何も残らなくなるまで「単語」を提供し続け、その時点でエラーが発生します。
vector<string> words;
string word;
while( cin >> word ) words.push_back(word);
ただし、ユーザーがすべての単語を 1 行に入力し、Enter キーを押して終了する必要がある場合は、getline を使用する必要があります。
// Get all words on one line
cout << "Enter words: " << flush;
string allwords;
getline( cin, allwords );
// Parse words into a vector
vector<string> words;
string word;
istringstream iss(allwords);
while( iss >> word ) words.push_back(word);
または、これを行うことができます:
cout << "Enter words, one per line (leave an empty line when done)\n";
vector<string> words;
string line;
while( getline(cin, line) )
{
// Because of the word check that follows, you don't really need this...
if( line.size() == 0 ) break;
// Make sure it's actually a word.
istringstream iss(line);
string word;
if( !(iss >> word) ) break;
// If you want, you can check the characters and complain about non-alphabet
// characters here... But that's up to you.
// Add word to vector
words.push_back(word);
}