Exercise 3-3 (Words, length)
Chapter_3 Exercise_3-2 Menu | Exercise_3-4 |
Exercise 3-3 TCP1, p. 227
Exercise 3-3. Write a program that uses a while() loop to read words from standard input (cin) into a string. This is an "infinite" while() loop, which you break out of (and exit the program) using a break statement. For each word that is read, evaluate it by first using a sequence of if() statements to "map" an integral value to the word, and then use a switch() statement that uses that integral value as its selector (this sequence of events is not meant to be good programming style; it’s just supposed to give you exercise with control flow). Inside each case, print something meaningful. You must decide what the "interesting" words are and what the meaning is. You must also decide what word will signal the end of the program. Test the program by redirecting a file into the program's standard input (if you want to save typing, this file can be your program's source file).
Words.cpp download
#include <iostream>
#include <string>
using std::string;
using std::cout;
using std::cin;
using std::endl;
int main()
{
int len; // length
string word;
while(true) // for ever
{
cin >> word;
if (cin.eof()) {break;} // end program
// else
len = word.length(); // word.size();
if (len < 3) // too short, ignored
{continue;} // go to the next while() iteration
else if (len < 10) // average word length
{
switch(len)
{
case 3: case 4:
cout << "Short word (" << len << "): " << word << endl;
break;
case 5: case 6:
cout << "Medium word length (" << len << "): " << word << endl;
break;
default:
cout << "Longer word (" << len << "): " << word << endl;
break;
}
}
else if (len < 20) // long word
{
switch(len)
{
case 10: case 11: case 12:
cout << "Long word (" << len << "): " << word << endl;
break;
default:
cout << "Very long word (" << len << "): " << word << endl;
break;
}
}
else // len >= 20 (too long)
{
cout << "Too long ("<< len << ")! Won't print it!" << endl;
}
}
return 0;
}
/*
g++ Words.cpp -o Words
./Words // input from keyboard
Hello! // Enter
Medium word length (6): Hello!
Hi // Enter (`Hi' too short, is just ignored)
Hi! // Enter
Short word (3): Hi!
Well... // Enter
Longer word (7): Well...
abracadabra // Enter
Long word (11): abracadabra
baraboumbosaurus rex // Enter
Very long word (16): baraboumbosaurus
Short word (3): rex
supercalifragilistic // Enter
Too long! Won't print it!
// Ctrl^D in Linux, Ctrl^Z+Enter in Windows (EOF)
./Words < Words.cpp // input from source file
./Words < Words // input from binary file
*/
Warning: You should be careful when printing the contents of a binary file in a terminal window. Some of it may be interpreted as a command.
Chapter_3 Exercise_3-2 Menu | BACK_TO_TOP | Exercise_3-4 |
Comments
Post a Comment