Hello, everyone. This is my first time to post questions here. Thank you in advanced for any help and suggestions.
I tried to write a loop that reads strings from standard input where the string is either "land", "air", or "water". The loop terminates when "xxxxx" (five x characters) is read in. Other strings are ignored.
It complied; however, when I type in "xxxxx", which is the sentinels, the program doesn't stop, it turns out to a infinite loop. The problem should be in the declaration and while loop condition, but I don't know how to fix it. please help, thank you ahead!
#include <iostream>
#include <cstring>
usingnamespace std;
int main()
{
string inputname;
string land, air, water;
string xxxxx;
int numberOfLand, numberOfAir, numberOfWater;
cout << "Please enter a word, either land, air, or water, and enter 'xxxxx' to quit the program." << endl;
cin >> inputname;
while (inputname != xxxxx)
{
if (inputname == land) {numberOfLand ++;}
if (inputname == air) {numberOfAir ++;}
if (inputname == water) {numberOfWater ++;}
cin >> inputname;
}
cout << "The number of 'land' is " << numberOfLand << endl;
cout << "The number of 'air' is "<< numberOfAir << endl;
cout << "The number of 'water' is "<< numberOfWater << endl;
return 0;
}
Just to add to what he said, if the sentinel string isn't going to be changing inside the program ever, I'd suggest declaring it as const (constant) as well. E.g.:
const string Sentinel = "xxxxx";
It's good style to do this, and it's far more self-explanatory in code seeing
while (inputname != Sentinel)
than seeing
while (inputname != "xxxxx")
and other references to arbitrary values littered throughout. Perhaps this is more important in larger applications where you'll be reusing certain arbitrary values throughout the code, but still a good habit to get into early on.
This also: if (inputname == land) {numberOfLand ++;}
probably should be:
if (inputname == "land") {numberOfLand ++;}
If this is the situation, then you won't need the variables land, air water.
Otherwise, assign a value to the variables land, air water.
Initialising variables is one of the main sources of error in programming. One of my main source of error is failing to read things properly!! Ha har !!