Stuck in an endless loop
When I run this program for a class, I get stuck in an infinite loop whenever I enter '|' to end the while loop. I feel like I am missing something obvious.
This issue is on page 126 of Bjarne Stroustrup's C ++ Programming book, but as a quick estimate, I just have to find the largest and smallest numbers that the user has typed and return information about it. Entering in '|' has to break out of the loop so I can go to the part where it gives information about all the numbers entered, but whenever I type that character (or any character, 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 used VS13 in class and didn't have this problem, but now I am coding in notepad ++ and using PuTTY to compile at home (although I doubt it has anything to do with it).
source to share
You are comparing a character to double
here:
if (current_num == '|')
And this comparison will never do what you want.
Read the symbol first, compare it to '|'
, then double-convert it if necessary.
Note:
For your entry, the ASCII value '|'
is 124, so if you enter 124 your loop ends ...
source to share
The problem is here:
if(current_num == '|'){
}
Instead, read in std::string
and parse it to double.
Thus, the modified snippet will look something like this:
while (true)
{
string strNum;
double current_num;
cout << "enter a double \n";
cin >> strNum;
if (strNum == "|")
break;
istringstream strm(strNum);
strm >> current_num;
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";
}
source to share