Pętla while

0

Chciałbym aby po wpisaniu złej liczby program powiedział, że wystąpił błąd oraz abyś wprowadził liczbę jeszcze raz (jesli blad to nie zwiększaj próby). Jak wyjść z drugiego while'a?

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main()
{
    int liczba, strzal, strzal2, proba=0;
    bool czy_poprawna;

    cout << "Losuje liczbe z zakresu 1..1000" << endl;
    srand(time(NULL));
    liczba = rand()%1000+1;
    cout << liczba << endl;

    do
    {
    proba++;
    cout << "Zgadnij jaka (proba nr " << proba << "): ";
    cin >> strzal;
    czy_poprawna = cin.fail();

        while(czy_poprawna)
        {
            cin.clear();
            cin.sync();
            cout << "BLAD! " << proba << ": ";
            cin >> strzal;
        }




    if(strzal > liczba) cout << "Za duzo!" << endl;
    else if(strzal < liczba) cout << "Za malo!" << endl;
    else cout << "Brawo! Wygrales w " << proba << " probie. Wylosowana liczba to " << liczba << endl;

    }while(strzal!=liczba);


    return 0;
}
0
#include <iostream>
#include <random>
#include <string>
#include <cassert>

namespace strongly_typed {
	struct randomized_number {
		int value;
	};
	
	struct player_input {
		int value;
	};
}

strongly_typed::randomized_number random_number(int min, int max) {
	static std::default_random_engine generator;
	return { std::uniform_int_distribution<>{min, max}(generator) };
}

strongly_typed::player_input read_player_input() {
	int result;
	while(!(std::cin >> result)) {
		std::cin.clear();
    	std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
	}
	return { result };
}

bool is_player_right(strongly_typed::randomized_number rn, strongly_typed::player_input input) {
	return rn.value == input.value;
}

std::string hint(strongly_typed::randomized_number randomized_number) {
	return std::string("(randomized number: ") + std::to_string(randomized_number.value) + ")";
}

std::string hint(strongly_typed::randomized_number randomized_number, strongly_typed::player_input input) {
	assert(randomized_number.value != input.value);
	return std::to_string(input.value) + " is too " + (input.value > randomized_number.value? "big" : "small");
}


int main() {
	auto const min = 1;
	auto const max = 10;
	auto const randomized_number = random_number(min, max);
	
	std::cout << hint(randomized_number) << std::endl;
	for(int attempt_no = 0 ;; attempt_no += 1) {
		auto player_input = read_player_input();
		if(is_player_right(randomized_number, player_input)) {
			break;
		}
		std::cout << hint(randomized_number, player_input) << std::endl;
	}
	
	std::cout << "taddah, " << randomized_number.value << " is the right answer" << std::endl;
	return 0;
}

http://melpon.org/wandbox/permlink/kki3Zx99YQDGjZr1

0

hehe dzieki :P

1 użytkowników online, w tym zalogowanych: 0, gości: 1