0

私はC++の初心者で、do / whileループの演習を行っていましたが、正しくループしないことは言うまでもなく、状態を認識するのに問題があります。このような単純な問題をどのように解決するかについて、良い基盤を教えていただけますか?文字列を使用して、do/whileループの条件を満たすようにします。

#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main ()
{
    double mean = 0;
    string continuer;
    do
    {
        cout << "Do you want to proceed?" << endl;
        getline (cin, continuer);
        cout << "something" << endl;
        cin >> mean;
    }
    while (continuer == "Y" || continuer == "y");

    return 0;
}
4

2 に答える 2

1

あなたの質問とコメントから私が集めたものは、ユーザーの意志でループを反復したいということです。

charこのように、そのための変数が必要です。

string input ;
int number = 0 ;

do
{
  cout << "Please enter a number" << endl ;
  cin >> number ;
  cout << "If you want to continue, Press Y" << endl ;
  cin >> input ;

} while (input == "Y" || input == "y") ;

この do-while ループは、ループ実行の最後に条件がチェックされるため、少なくとも 1 回は実行されます。したがって、最初に尋ねられたときにユーザーが Y を押さなくても、このループは 1 回実行されます。以後、条件を満たしている限り継続します。

do-while ループの詳細については、こちらをご覧ください。

http://www.cplusplus.com/doc/tutorial/control/

于 2012-11-10T11:56:09.023 に答える
0

何が見えますか?ループの本体は少なくとも1回実行する必要があります。それは起こりますか?

また、Continuerは、「Y \ n」のように、1文字より長くすることができます。そのためにテストしてください。

これが私がすることです:

#include <string>
#include <sstream>
using namespace std;



    int main ()
    {
        double number = 0;
        string continuer;
        int loop = 0
        do
        {

            cout << "Do you want to proceed?" << endl;
            getline (cin, number);
            cout << "something" << endl;
            cin>> mean;
            getline (cin, continuer);

            cout << "Your answer was '" << continuer << "'." << endl;
            loop = strcmp("Y", continuer);
            if (loop != 0) strcmp("y", continuer);
            if (loop == 0) cout << "Your choice is to stop." << endl;
            else cout << "Your choice is to continue." << endl;
        } while (loop == 0);
        cout << "Bye" << endl;
        return 0;
    }

使用している言語とアルゴリズムに十分な自信が持てるようになるまで、できるだけ明確にしてください。何が起こっているかを確認する方が簡単で、機能する場合は「cout」行を簡単に削除できます。

于 2012-11-10T11:45:33.093 に答える