开发者

C++ How can I tell if a value is assigned into a variable?

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

like

cout << "Enter 开发者_Python百科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?


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

So your code will look like:

if( x.defined() )
  ...


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).


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


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


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.


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.


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..

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜