Home > Software design >  How can I set User Input from Code in C ?
How can I set User Input from Code in C ?

Time:10-02

I am creating a test for a function which gets the user input with std::cin, and then returns it. The test just needs to check if the input from the user, is the one actually returned. Problem is, the test should be automated so I can't manually react to the std::cin prompt. What can I do to set the input with code?

CodePudding user response:

I wouldn't bother with automation or redirection of the std::cin functionality.
From personal experience it always get much more complicated than it has to be.
A good approach would be to separate your behavior.

Bad:

void MyFunction()
{
    std::string a; 
    std::cin >> a;
    auto isValid = a.size() > 1;
}

Better:

bool ValidateInput(const std::string& myString)
{
    return myString.size() > 1;
}

void MyFunction()
{
   std::string a; 
   a << std::cin();
   auto isValid = ValidateInput(a); 
}

There are more complex solutions to this with std::cin.rdbuf. You could adjust rdbuf - use this only if you don't have control on the function.

For example:

#include <sstream>
#include <iostream>

void MyFunc()
{

    std::string a;
    std::cin >> a;
    auto isValid = a.size() > 1;

    if (isValid)
    {
        std::cout << a;
    }
}

int main()
{
    std::stringstream s;
    s << "Hello_World";
    std::cin.rdbuf(s.rdbuf());

    MyFunc();
}

Always separate the input functions from the validation functions and the processing functions.

Best of luck!

  • Related