user8026040
user8026040

Reputation:

Is there a way to set the value of a variable to empty in C++?

I have a program which prints a statement based on inputs. The print statement prints using all inputs, but I only want it to print inputs which are actually given. For instance:

std::cout << "-Number: " << number < "-Letter: " << letter << "-String: " << str << "-Sum: " << sum << std::endl; 

(for the purpose of demonstration, the variables above are arbitrary, this is just to show a point)

So this print statement is called after every iteration of a loop. The values can be anything, but I do not want it to print if a value was not received. Ideally, this would be done like so:

// Get input... Then print statement... 
// If input was not received for a value (i.e. it equals none) then skip that value
std::cout << "-Number: " << number < "-Letter: " << letter << "-String: " << str << "-Sum: " << sum << std::endl; 
number = none, letter = none, str = none, sum = none // reset inputs and repeat loop

(Once again, the above is pseudo-code for the purpose of demonstration)

Is this possible in C++?

Upvotes: 0

Views: 902

Answers (1)

Thomas Caissard
Thomas Caissard

Reputation: 866

If you have C++17 or a later version see optional. Prior to that, you would need to wrap your type into a proper struct that would mimic what optional does (of which you can find various implementation on the net, e.g. https://github.com/TartanLlama/optional).

In your example, you could do:

std::optional<int> number;

// Puts a value inside number
if (some condition)
    number.value() = 44;
// Set number to invalid
else number.reset();

std::cout << "Number: " << (number ? number.value() : "Some Default Value You want to Show" << std::endl;

std::optional has an operator bool() which tells you if you correctly have a value in your std::optional. Also note that your std::optional is invalid by default if you call the default constructor (see https://en.cppreference.com/w/cpp/utility/optional/optional).

Upvotes: 1

Related Questions