0

センチネル値が入力されるまで、いくつかの 1 単語の入力を求める C++ プログラムを作成しようとしています。この値 (つまり「完了」) が入力されると、プログラムはユーザーが入力したすべての単語を出力する必要があります。

私は一般的な形式を持っています。ただし、これは文字列の複数の値を保存しません...どんな助けも素晴らしいでしょう、ありがとう。

#include <iostream>
#include <cstring>

using namespace std;

int main()
{
    string word;
    word = "";
    cout << "Enter the next bla bla now:   " ;
    cin >> word;


    while ( word != "complete" )
    {
        cout << "The previous bla bla was:  " << word << endl;
        cout << "Enter the next bla bla now: ";
        cin >> word;

    }

    cout << "Your phrase..bla bla bla is :  " << word << endl;

    return 0;
}
4

3 に答える 3

1

結果をベクトルに保存してから、次のようにループできます。

#include <iostream>
#include <string>
#include <vector>

int main() {
    std::string str;
    std::vector<std::string> strings;
    while(std::getline(std::cin,str) && str != "complete") {
        strings.push_back(str);
    }
    std::cout << "Your strings are: \n";
    for(auto& i : strings)
        std::cout << i << '\n';
}

このコードは、「完了」という単語が見つかるまでユーザー入力を求め続け、入力された文字列をベクトル コンテナーに挿入し続けます。「完了」という単語が入力されると、ループが終了し、ベクターの内容が出力されます。

これは C++11 の for-range ループを使用していることに注意してください。これは、反復子またはstd::copyを使用して置き換えることができますstd::ostream_iterator

于 2013-01-30T04:23:33.303 に答える
1

集合文字列を使用して、これらの単語を連結することができます。要するに...

#include <iostream>
#include <cstring>

using namespace std;

int main()
{
    string word;
    string allWords = "";

    word = "";
    cout << "Enter the next bla bla now:   " ;
    cin >> word;


    while ( word != "complete" )
    {
        allWords += word + " ";
        cout << "The previous bla bla was:  " << word << endl;
        cout << "Enter the next bla bla now: ";
        cin >> word;
    }

    cout << "Your phrase..bla bla bla is :  " << allWords << endl;

    return 0;
}

編集

振り返ってみると、ベクターを使用すると、後でより使いやすくなり、別の目的でこれらの単語を反復処理できるようになります。私の解決策は、何らかの理由でこれらの単語を 1 つの文にまとめたい場合にのみ役立ちます。

于 2013-01-30T04:23:42.870 に答える
1

単語を保存するために使用できますstd::vector<std::string>。以下のコードは、独自のコードを少し変更するだけで機能します。

#include <vector>
#include <string>
#include <iostream>
#include <iterator>

int main()
{
    std::vector<std::string> words;
    std::string word;
    std::cout << "Enter the next bla bla now:   " ;

    while (std::cin >> word && word != "complete" )
    {
      words.push_back(word);
      std::cout << "You entered:  " << word << std::endl;
    }

    std::cout << "Your word collection is:  " << std::endl;
    std::copy(words.begin(), words.end(), 
              std::ostream_iterator<std::string>(std::cout, " "));

    return 0;
}
于 2013-01-30T04:23:43.873 に答える