1

I'm making a short database application where people can assign variables to something.

like

cout << "Enter song ID#": cin >> x; 

But I want to prompt the user if there was already a value stored in x. Is there a way to discern between the garbage values initially stored in x and other values?

that way I can do something like

cout << "Enter song ID#": cin >> x; if (isUsed(x)) cout << "Do you want to overwrite this value?"; 

EDIT x is actually a dynamic array so I cannot initialize it..or can I?

7 Answers 7

2

I believe you need this: http://www.codeproject.com/KB/cpp/value_t.aspx

So your code will look like:

if( x.defined() ) ... 
Sign up to request clarification or add additional context in comments.

2 Comments

made a simple program, didn't work. error C2228: left of '.defined' must have class/struct/union type is 'int'
Define this: typedef t_value<int, 0, MIN_INT> int_v; Then define your 'x' as int_v x; Then do cin >> x._v; And if( x.defined() ) ...
2

You must initialize x to hold some recognizable value which the user cannot produce, or use a boolean variable which is flipped the first time x is set (then check that variable to determine if your value is meaningful).

3 Comments

I'm doing a dynamic array and struct actually, or I would have done this
So create the bool dynamically too? The two approaches I suggested work for both static and dynamic data.
thanks, I was just wondering if there was a hidden function in c++ that avoided this complication, apparently not
1

If you are able to deviate from the standard you could decide to use boost::optional for this.

Comments

0

No. All you can do is use another variable as a sentinel to track whether a value has been assigned to it.

Comments

0

Unless you know a priori what sort of values will be stored in x by your program, there's no way to tell. And of course there's always the chance that the garbage will randomly be in the acceptable range.

But you're not required to live with garbage. Initialize x to some known value that can signal "unused" to you.

Comments

0

There is no way you can discern between the garbage values initially stored in x and other values. But you can write your program in such a way that ensures that when you read the value from the variable, the variable is either initialized or assigned with some value.

Comments

0

Initialize x..

Say,

int x = -1000;

Now every time check for that value -1000.

And of course the value you initialize with x should be a non probable value for the user..

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.