开发者

C++: How to make a program read words instead of character? And how to make the program stop reading when entering a "lone" character?

开发者 https://www.devze.com 2023-02-16 12:48 出处:网络
I need help with Excercise 7 in Chapter 6 of Stephen Pratas \"C++ Primer Plus 5th Edition\". The excercise is to write a program that reads input from the user as \"words\" and count the vowels and c

I need help with Excercise 7 in Chapter 6 of Stephen Pratas "C++ Primer Plus 5th Edition".

The excercise is to write a program that reads input from the user as "words" and count the vowels and consonants or "other symbol" that each word begins with. To stop the program the user must enter A LONE q.

What I think i have figured out:

I only need the program to read the first character of each word since it only counts the beginning characters.

To know that the input is a word the program will detect if a "space" is before the character, To be more precise that first a "space" come and then directly followed by a character/symbol.

Then to detect if it is a alphanumeric character i will use "isalpha()" on the character and use if/if else statements to let the program detect if it is a vowel or a consonant if we assume that isalpha() is true.

If isalpha is false the program will count the symbol as other.

The loop will continue as long as no lone q appears. So I must be able to write word like quiet, quit and so on without the program stopping the loop.

So to my problems:

  1. How to make a loop check for the c开发者_StackOverflow中文版onditions described above? (a space followed by a character/symbol)
  2. And how do you define a lone q?(I dont mean the "command" define here) and use it as exit condition for the loop.


  • You can use a local variable to remember the previous character read from input, reading one character at a time.

  • A lone character is a word of length 1.


The istream operator >> when applied to a string reads a single word.
The istream operator >> when applied to a character reads a single character

  std::string  word;
  std::cin >> word;

  char         letter;
  std::cin >> letter; // read first no white space character.

  // Normally all >> operators drop prefix white space before doing their actual work
  // Hence the letter above will ignore whitespace characters. 
  // But you can suspend the dropping for prefix whitespace like this.

  std::cin >> std::noskipws >> letter.


There are two possible solutions, but the easiest is just to use the fact that your definition of "word" is exactly that used by the >> on a string. So something like:

std::string word
while (src >> word) ...

will result in a word each time.

For other definitions of word, you'll probably have to define a state machine, with states like inWord, betweenWords and whatever, and implement the corresponding state transitions.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号