2010-08-31 82 views
1

我已经开始学习C++,并且正在通过C++ Primer Plus书中的一些练习。练习自学帮助

在第二章的习题5个是:

编写使用 焦炭和循环的数组在 时间,直到输入完成的字读一个字的程序。 然后,程序应该报告输入的字数 (不包括完成的 )。样品运行看起来是这样的:

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. 

您应该包括CString的头 文件并使用的strcmp()函数来 进行对比测试。

很难弄明白这一点。这将是容易得多,如果我可以的if语句和逻辑运算符使用,但我只能使用唯一的:

  1. 循环
  2. 关系表达式
  3. 字符数组

分支statments(即如果,case/switch)和逻辑运算符是不允许的。

任何人都可以给我提示,以推动我朝着正确的方向吗?

编辑:澄清。输入必须是一个字符串。所以,一个输入的几个词。

+3

如果一本书禁止使用丑陋的拐杖是一回事,但这是禁止你使用你应该用来解决问题的工具。为什么不跳过这个练习。 – Potatoswatter 2010-08-31 05:53:49

+3

@Patatoswatter:...或者忽略无意义的限制,而是写出最明智的代码,以便产生正确的最终结果。 – 2010-08-31 05:57:15

+0

大声笑,我在想同样的事情。几分钟后,我质疑这是否是一个很好的锻炼问题。 – ShrimpCrackers 2010-08-31 06:01:28

回答

2

编辑来完成:哎呀,规范说要读入字符数组......我不会麻烦编辑,这真的很愚蠢。 std::string也包含一个char数组!

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) ; 

我喜欢

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

提示:一个循环也可以作为一个条件......

2

使用此伪代码:

while (input != done) 
    do things 
end-while 
0
integer count 
char array input 

count = 0 
read input 
while(input notequal "done") 
count++ 
read input 
done 
print count 
  • input notequal "done"部分可以 可以为strcmp(input,"done")完成。如果 返回值是0是手段 输入相同"done"
  • 读取输入可以使用cin
+0

这有效,但输入必须是一个字符串。 – ShrimpCrackers 2010-08-31 06:00:13

0

你应该先定义字符数组一个最大LEN。然后做while while循环就足够了。你可以用strcmp函数检查字符串是否相等。这应该没问题。