开发者

Exercise Self Study Help

I've started learning C++ and am working through some exercises in the C++ Primer Plus book.

In chapter 5 one of the exercises is:

Write a program that uses an array of char and a loop to read one word at a time until the word done is entered. The program should then report the number of words entered (not counting done). A sample run could look like this:

Enter words (to stop, type the word done):
anteater birthday category dumpster
envy finagle geometry done for sure
You entered a total of 7 words.

You should include the cstring header file and use the strcmp() function to make the comparison test.

Having a hard time figuring this out. It would be much easier if I could use if statements and logical operators but I'm restricted to using only:

  1. Loops
  2. Relational Expressions
  3. char arrays

Branching statments (ie if, case/switch ) and logical operators are not allowed.

开发者_如何学C

Can anyone give me hints to push me in the right direction?

Edit: Clarification. The input must be one string. So, several words for one input.


Edit: oops, spec says to read into an array of char… I'm not going to bother editing, this is really stupid. std::string contains an array of char too!

cin.exceptions( ios::badbit ); // avoid using if or && to check error state

int n;
string word;
for ( n = 0; cin >> word, strcmp( word.c_str(), "done" ) != 0; ++ n ) ;

I prefer

string word;
int n;
for ( n = 0; cin && ( cin >> word, word != "done" ); ++n ) ;


Use this pseudo-code:

while (input != done) 
  do things
end-while


HINT: A loop could also act as a conditional...


integer count
char array input

count = 0
read input
while(input notequal "done")
 count++
 read input
done
print count
  • The input notequal "done" part can be done as strcmp(input,"done"). If the return value is 0 is means input is same as "done"
  • reading input can be done using cin


You should define a max len for char arrays first. Then a do while loop would be sufficient. You chould check the string equality with the strcmp function. That should be ok.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜