When I'm running this program for class, I'm getting stuck in an infinite loop whenever I enter a '|' character to end the while loop. I feel like I'm missing something obvious.
This problem is found on page 126 of Bjarne Stroustrup's C++ Programming book, but as a quick rundown, I'm just supposed to find the largest and smallest numbers that are typed in the by the user and return info on it. Typing in '|' is supposed to exit the loop so that I can get down to the part where it gives information about all the numbers inputted, but whenever I type that character (or any character that's not a number), it creates an infinite loop.
Here is my code.
int main()
{
vector<double> nums;
while (true)
{
double current_num;
cout << "enter a double \n";
cin >> current_num;
if (current_num == '|')
break;
nums.push_back(current_num);
sort(nums.begin(), nums.end());
cout << nums[nums.size()-1] << " is the largest so far.\n";
cout << nums[0] << " is the smallest so far.\n";
}
cout << nums[nums.size()-1] << " is the largest number.\n";
cout << nums[0] << " is the smallest number.\n";
cout << "Number of values entered: " << nums.size() << '\n';
double sum = 0;
for (int k = 0; k<nums.size(); ++k)
sum += nums[0];
cout << "Sum of all values: " << sum << '\n';
for (int j=0; j<nums.size(); ++j)
cout << nums[j] << ' ';
return 0;
}
I was using VS13 in class and I wasn't having this problem, but now I'm coding in notepad++ and using PuTTY to compile at home (although I doubt this has anything to do with it).
You are comparing a character with a double here :
if (current_num == '|')
And this comparison will never do what you want it to do.
Read a character first, compare it with '|', then do a double conversion if necessary.
Note:
For your record the ASCII value of '|' is 124, so if you enter 124 your loop will end...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With