As it is now the user can press enter without typing anything and I do not want the user to be able to create objects without these values.
I fought about an if, something like if(Foo != "" || Bar != "") but I don't know where to put it, and what to return if the user has not made an input.
I would like it to loop back and let the user try again, but I need help with this...
Ensuring that the invariant for an object is established should ideally be done in a constructor. (Creating an object with data entered by the user is only one of many different possible ways for crating an object).
The classical way for the constructor to report an error is by throwing an exception. With that, any user of the class can create objects in a way that is most appropriate for that user's particular use case, without violating its encapsulation.
Something like:
1 2 3 4 5 6 7 8 9 10 11 12 13
struct A
{
A( const std::string& s ) : str(s)
{
if( str.empty() || !std::isdigit(str[0]) )
throw std::domain_error( "the string does not start with a digit" ) ;
}
// ...
private:
std::string str ; // invariant: str is not empty and must start with a digit
};
And then:
1 2 3 4 5 6 7 8 9 10 11
A make_a_from_user_input()
{
std::string s ;
std::getline( std::cin, s ) ;
try { return A(s) ; }
catch( const std::exception& e )
{ std::cerr << "error in input: " << e.what() << ". try again\n" ; }
return make_a_from_user_input() ;
}