刚开始看C++ PRIMER PLUS 5TH,有个有关问题不太明白,请高手们指点下多谢
刚开始看C++ PRIMER PLUS 5TH,有个问题不太明白,请高手们指点下谢谢
#include <iostream>
#include <cstring> // prototype for strcmp()
const int STR_LIM = 50;
int main()
{
using namespace std;
char word[STR_LIM];
int count = 0;
cout < < "Enter words (to stop, type the word done):\n ";
while (cin > > word && strcmp( "done ", word))
++count;
cout < < "You entered a total of " < < count < < " words.\n ";
return 0;
}
这个程序是输入一串字符,遇到done停止,计算前面输入单词的个数,但不明白是怎么实现的,就是while那句比较费解,请高手指点下啊
------解决方案--------------------
while (cin > > word && strcmp( "done ", word))
输入字符串到word成功,并且字符串内容不为done
则循环
------解决方案--------------------
首先看&&,具有短路求值的性质
然后看cin> > word,这个就是输入字符串到word数组中,如果输入了文件结束符,那就是false,直接短路退出循环
最后看strcmp(),就是比较word和 "done ",如果相同返回false,也会退出循环
#include <iostream>
#include <cstring> // prototype for strcmp()
const int STR_LIM = 50;
int main()
{
using namespace std;
char word[STR_LIM];
int count = 0;
cout < < "Enter words (to stop, type the word done):\n ";
while (cin > > word && strcmp( "done ", word))
++count;
cout < < "You entered a total of " < < count < < " words.\n ";
return 0;
}
这个程序是输入一串字符,遇到done停止,计算前面输入单词的个数,但不明白是怎么实现的,就是while那句比较费解,请高手指点下啊
------解决方案--------------------
while (cin > > word && strcmp( "done ", word))
输入字符串到word成功,并且字符串内容不为done
则循环
------解决方案--------------------
首先看&&,具有短路求值的性质
然后看cin> > word,这个就是输入字符串到word数组中,如果输入了文件结束符,那就是false,直接短路退出循环
最后看strcmp(),就是比较word和 "done ",如果相同返回false,也会退出循环