How to detect when the user enters something invalid or wants to terminate the program first?

Asked

Viewed 194 times

0

I was doing an exercise in C++ that takes the smallest and the largest number typed by the user, I tried to leave something more automatic, where he goes typing until he doesn’t want more. So I’m trying to define that if the user type 'k' for example, the code stops and checks is done only with the numbers that were typed before. and if it enters another letter other than the 'k' that is for the output, the program informs that n is a valid value.

I was able to make the code, and it was working, but I couldn’t get past this step of recognizing k or another letter, since the array that receives user values is int/float. and the character 'k' is of the char type, then gives error in the comparison.

Is there a way to make comparisons between different variable types? or convert, something? I’m still beginner in C++

float valor[20];
 float menor;
 float maior{ 0.0 };

 std::cout << "Informe os valores para vermos qual é o menor e maior numero!\n(Maximo permitido são 20 valores)(pressione K para encerrar)\n";
    for (int i = 0; i < 19; i++) {
        std::cin >> valor[i];
        menor = valor[0];
            if (valor[i] == 'k') {
                i = 20;
            }
        menor = valor[i]<=menor?valor[i]:menor;
        maior = valor[i]>maior?valor[i]:maior;
        system("cls || clean");
    }
std::cout << "\nO menor numero digitado foi: " << menor;
std::cout << "\nO maior numero digitado foi: \n" << maior;
  • 2

    Please add the code you produced so that someone can better understand the context and help you.

  • added the code

  • You can read the line with getline and check its contents as a character and, if applicable, convert the read string to a float using the function stof. To not restrict the values that can be informed also use the initial value of higher as the first number read.

2 answers

1

Maybe what you need is something like:

#include <algorithm>
#include <iostream>

int main()
{
    int menor;
    int maior;

    std::cin >> menor;
    maior = menor;

    for(int i = 0; i < 19; i++)
    {
        int atual; std::cin >> atual;
        if(!std::cin) // verifica se a entrada é válida
        {
            break;
        }

        menor = std::min(atual, menor);
        maior = std::max(atual, maior);
    }
    std::cout << "Maior: " << maior << '\n';
    std::cout << "Menor: " << menor << '\n';
}

Notice that the first value is read before the loop. Also note that, the loop breaks if whichever invalid value is entered.

Although it is a trivial operation it is preferable to use the functions Std::min and Std::max instead of doing everything "manually" so that the code is more readable.

1

Hello! Try the following approach.

Considerations:

If you are to allow number "0" then you will have to check in a slightly different way the entered value and comparison.

Another thing, I assumed that the smallest number is a high number, but, you can improve this by putting the smallest number equal to the typed value when the smallest is with "0" for example.

#include <algorithm>
#include <iostream>

int main(){
    float valordigitado;
    float valor[20];
    float menor=100000000;
    float maior{ 0.0 };

    std::cout << "Informe os valores para vermos qual é o menor e maior numero!\n(Maximo permitido são 20 valores)(pressione K para encerrar)\n";

    for (int i = 0; i < 19; i++) {
        std::cin >> valordigitado;
        if ( valordigitado == 'k' ) {
           i = 20;
        }
        else if ( valordigitado > 0 ) {
           valor[i]=valordigitado;           
           menor = valor[i]<menor?valor[i]:menor;
           maior = valor[i]>maior?valor[i]:maior;

        }
    }

    //system("clear");
    std::cout << "\nO menor numero digitado foi: " << menor;
    std::cout << "\nO maior numero digitado foi: " << maior;
    std::cout << "\n";
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.