简体   繁体   中英

“Update” line in CMD, C++

I need to get input from the user but if an invalid argument is passed in then the "Invalid" messages stack up.
I'd prefer if it just kept printing the invalid on the same line and then once a correct input is given it resets the line to original question.
I've seen the talk of using \r but it does not seem to work for me.

bool getInput(std::variant<std::string, float>* toOut, bool* restart, bool* qUsed){

    std::string userIn;
    std::cin >> userIn;

    if(userIn == SENTINAL){
        *restart = true; 
        return false;
    }

    try {

        *toOut = std::stof(userIn);

    } catch(std::invalid_argument) {

        if(userIn == TO_SOLVE && !*qUsed){
            *toOut = TO_SOLVE;
            *qUsed = true;
        } else {
            std::cout << "\rInvalid, please try again : ";
            getInput(toOut, restart, qUsed);
        }

    }

    return true;

}

I haven't put the resetting to original question yet.
When I run this the \r does nothing.
Why is this / what's the best way to "update" cmd text?

if (userIn != required_string)
{
//call the function in itself
}

this is called recursion

not sure what calling this code looks like from the other parts of your project.

you could also return true if correct and return false if else... then just have a while loop or something till the get it correct

seems like there is a lot going on here for just a user input

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM