0

I was given a pseudo code to translate into C++ :

    Set a Boolean variable “first” to true.
    While another value has been read successfully
          If first is true
          Set the minimum to the value.
          Set first to false.
          Else if the value is less than the minimum
          Set the minimum to the value.
    Print the minimum

And here are my codes :

bool first = true;
bool read_value = true;
int value = 0;
int minimum = 0;
cout << "Enter an integer : " ;
cin >> value;
while(cin.hasNextInt())   // error here
{
    cout << "Enter another integer : " ;
    cin >> minimum;
    if( first == true){
        minimum = value;
        first = false;
    }else if ( value < minimum){
        minimum = value;
    }
}
cout << minimum;

system("PAUSE");
return 0;

There is error at the hasNextInt there. And I don't really know what the pseudo code wants. Can somebody explain to me?

Thanks in advance.

Voice
  • 194
  • 6
Rauryn
  • 177
  • 2
  • 4
  • 16

3 Answers3

1

There is no hasNextInt() function in the standard C++ libraries (and that's why you can't compile). There is one in Java, however!

Victor Sand
  • 2,270
  • 1
  • 14
  • 32
  • @Rauryn You're on the right track, it's just not how you do it. You need `while (cin >> value)`. – jrok Apr 24 '13 at 13:26
  • @jrok So what am I supposed to change? The Enter another integer which is in the while loop keep iterating. – Rauryn Apr 24 '13 at 13:32
  • 1
    You'll stop the loop when you enter something that can't be interpreted as an integer - that's when the condition `cin >> value` evaluates to false. You can signal EOF to cin by entering Ctrl+Z (Windows) or Ctrl+D (linux), for example. – jrok Apr 24 '13 at 13:36
  • Oh that's what the pseudo code means? The system keep on prompting user to enter integer until there's something which is not integer. Then it will filter out the minimum? – Rauryn Apr 24 '13 at 13:39
0

This is closer to code you want:

cout << "Enter an integer : " ;
while( cin >> value )
{
    if( first == true){
        minimum = value;
     first = false;
    }else if ( value < minimum){
        minimum = value;
    }
    cout << "Enter another integer : " ;
}
Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
0

That is stupid pseudo code. We can do better without some worthless bool...

int min = std::numeric_limits<int>::max();

for(int val; cin >> val)
{
    if(val < min)
        min = val;
}

cout << "Minimum: " << min << '\n';
David
  • 27,652
  • 18
  • 89
  • 138
  • There's no choice. I am new to C++. And I've to follow the question. Thanks anyway. – Rauryn Apr 24 '13 at 13:30
  • @Rauryn This is homework I presume? The answer is "This is stupid pseudo code, here's a better way..." – David Apr 24 '13 at 13:30