Hello! I'm very new to C++ and I have a program I need to write that I do not know how to start. The prompt is: "A loop that keeps reading words until it runs out of input, and prints the words that are alphabetically first and last. You can assume that the words are actual words and all in lowercase." This is what I have so far, but I am very confused on how to continue. Thank you!
int main ()
{
while (cin>>word)
{
cout<<"Enter a word"<<".\n";
string word;
cin>>word;
}
}
If you are on Windows you can enter ctrl + z to signal end of file which makes the loop break. You could modify this easy to make a special word break the loop also.
It's saying that the loop will stop once the user input stops, so whenever the user to done giving input the loop needs to stop. I was trying to use a while statement, but I don't know what the condition would be if the loop stops based on user input.
But is it possibly to do this program without using vectors and just using loops?
Yes. Rather than storing all of the words, you need just three variables, to hold the current word, the lowest word and the highest word (in alphabetical sequence).
I was trying to use a while statement, but I don't know what the condition would be if the loop stops based on user input.
The original code was almost heading in the right direction.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
int main()
{
string word;
cout << "Enter a word.\n";
while (cin >> word)
{
// add the code here
// to do something with the word
cout << "Enter a word.\n";
}
}
Note: if you redirect the input from a file, the prompts are not really necessary. But if entering by hand from the keyboard, they probably help. In that case use CTRL-Z and ENTER (windows) or CTRL-D (other os).
Would an if statement work when comparing the words? As in, how would the if statement know if the word was higher or lower to the current word in terms of it being alphabetically?
If a user would to input the words, "chair, apple, cup, tree" then the program would put the words in alphabetically order, but only print the first and last word on that last. So it would output would be "apple and tree".
It's not clear what you mean. You should try it out in your code instead of just thinking about it. Your first step is to write some pseudocode, here's a start:
1. get a word
2. is it higher than the highest word?
2a if it is ...
3. is it lower than the lowest word?
3a if it is ...
4 get another word