HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

Enabling stack overflow protection with Y/N prompt

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
stackpromptwithoverflowprotectionenabling

Problem

This asks the user if they would like to enable stack overflow protection. If they enter yes (Y or y), then a Boolean SOProtection is set to true. If they enter no (N or n), then SOProtection is set to false.

If neither Y, y, N nor n is entered, then it clears the input stream (to protect against a case where multiple characters are entered, which results in the input being run through multiple times).

How can this code be optimized (in both efficiency and performance)?

bool SOProtection;
char checkSOProtection;

while(true){
    std::cout > checkSOProtection;

    if(checkSOProtection == 'Y' || checkSOProtection == 'y'){
        SOProtection = true;
        break;
    }

    if(checkSOProtection == 'N' || checkSOProtection == 'n'){
        std::cout ::digits10);
}

Solution

Your ignore can produce some erratic results, depending upon the number of characters entered by the user. Rather than:

std::cin.ignore(std::numeric_limits::digits10);


You might want to go with:

std::cin.ignore(std::numeric_limits::max(), '\n');


Which will ignore all of the entered characters up to the end of the input line. That way you don't start going round the loop multiple times, or with left over characters if the user enters:


asdfasdfasdfasdfasdf

I'd also consider moving the warning to before the question. Telling me there may be a seg fault after I've already selected that route seems like a waste of time. I'd prefer to have that information prompted before I select Y/N (or given the question have it assume that I already know that information).

Code Snippets

std::cin.ignore(std::numeric_limits<char>::digits10);
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

Context

StackExchange Code Review Q#142955, answer score: 2

Revisions (0)

No revisions yet.