まず、 a に読み込むstd::string
ので、長さを気にする必要はありません。これを行うとループ状態になるため、読み取り、すぐに成功したことを確認します。
std::string word;
while (std::cin >> word) // ...
これは、空白 (スペース、タブ、改行など) で区切られた文字列を読み取ります。次に、それらを に保存するstd::vector
ので、単語がいくつあるか心配する必要はありません。
std::vector<std::string> words;
std::string word;
while (std::cin >> word)
words.push_back(word);
次に、これをループして で始まる単語を出力する"stu"
には、さまざまなオプションがあります。標準ライブラリ アルゴリズムの使用をお勧めしますcopy_if
。これは述語(チェッカー関数) を取り、それを の各要素に適用しますvector
。述語が戻ってきた場合はtrue
、要素を別の場所にコピーします。この場合 (そして、これが少し面倒です)、std::cout
an と呼ばれる特別な種類の反復子を使用して、にコピーしostream_iterator
ます。
std::copy_if(std::begin(words),
std::end (words),
std::ostream_iterator<std::string>(std::cout, " "),
[](const std::string& word){ return word.find("stu") == 0; });
これはいくつかのC++11
機能 ( copy_if
、ラムダ、非メンバーbegin
/ end
) を使用します。裸のループを自分で書くこともできます (しないほうがいいです):
for (std::vector<std::string>::const_iterator it = words.begin();
it != words.end();
++it)
{
if (it->find("stu") == 0)
std::cout << *it << ' ';
}
同様の手法を使用して入力を読み取ることもできますが、(私の経験では) 上記のより一般的な方法を示しました。これが望ましいと主張する人もいますが、より奇妙なイテレータを使用しています。
std::vector<std::string> words;
std::copy(std::istream_iterator<std::string>(std::cin),
std::istream_iterator<std::string>(),
std::back_inserter(words));
istream_iterator
入力ストリームをコンテナのように扱う方法です。
したがって、次の 2 つのオプションがあります。
生のループを自分で書きます: while
and for
. これは、ほとんどの人、特に「初心者」が書く方法ですが、私は通常、低レベルのものを避けるために組み込み機能を使用することを好みます。適用している概念について考えてください。たとえば、「これらの単語が「stu」で始まる場合、これらの単語を画面にコピーしています」などです。
<algorithm>
もう 1 つのオプションは、ヘッダーで提供される機能を使用することです。私はこのオプションが好きですが、いくつかの奇妙なイテレータに頭を悩ませる必要があります。
編集:ちなみに、必要なヘッダーは<algorithm>
、、、、およびです。(生のループを記述した場合は削除できます)。<iostream>
<iterator>
<string>
<vector>
<algorithm>
<iterator>
もう一度編集してください。わかりました、これを書くのは嫌いですが、C
スタイルの文字列だけでそれを行う方法は次のとおりです。このようなネイキッド配列とポインターを扱うときは、非常に注意する必要があります。各ステップを説明するためにコードにコメントを付けました。このような完全な解決策を提供するだけではありませんが、各部分を説明する方法がわかりません。盗むだけでなく、学んでください。
#include <cstring>
#include <iostream>
typedef char FixedLengthString [51]; // 50 chars plus NUL-terminator
int main()
{
FixedLengthString words [10]; // assume you never have more than 10
// if you have no limit, this is harder
// need to do two things at once in the loop:
// - read no more than ten
// - read and check it succeeded
int read = 0; // outside the loop, as we need it later
for (; read < 10; ++read)
{
std::cin.width(50); // saves us from overflowing by reading too much
std::cin >> words[read];
// die if the read failed (end of input or something broke)
if (!std::cin) break;
}
// loop over however many we successfully read
for (int i = 0; i < read; ++i)
{
// compare the first 3 characters of the words with "stu"
if (std::strncmp("stu", words[i], 3)==0)
{
std::cout << words[i] << ' ';
}
}
}