[英]How does this program work
这是我的第一个C ++程序。 它打印输入中的单词数。
我的第一个问题是,它如何进入循环并增加计数? 每次输入空格字符都可以吗? 如果是这样,它怎么知道我要数单词?
using namespace std;
int main() {
int count;
string s;
count = 0;
while (cin >> s)
count++;
cout << count << '\n';
return 0;
}
我的第二个问题。 有人可以向我解释std命名空间对初学者意味着什么吗?
当您执行cin >>字符串时。 您将阅读一个单词并将其放入字符串中。 是的,它将逐字符读取char直到到达定界符。
标准表示标准。 标准C ++库位于std名称空间内。 您可以在不使用命名空间std的情况下进行重写或编码:
int main() {
int count;
std::string s;
count = 0;
while (std::cin >> s)
count++;
std::cout << count << '\n';
return 0;
}
我不鼓励新手使用using名称空间std语句,因为这很难理解发生了什么。
在您的代码中, cin >> s
尝试从输入流中读取std::string
。 如果尝试成功,则cin >> s
的返回值将隐式转换为true
,并且while循环继续进行,从而使计数器递增。 否则,当尝试失败时,while循环将退出,因为没有更多数据可从输入流中读取。
您可以使用std::distance
来计数单词,如下所示:
#include <iostream>
#include <algorithm>
#include <iterator>
#include <string>
int main() {
std::istream_iterator<std::string> begin(std::cin), end;
size_t count = std::distance(begin, end);
std::cout << count << std::endl;
return 0;
}
演示: http : //www.ideone.com/Hldz3
在此代码中,您将创建两个迭代器begin
和end
,并将它们都传递给std::distance
函数。 该函数计算begin
和end
之间的距离。 距离不过是输入流中字符串的数目,因为迭代器begin
对输入流中的字符串begin
迭代,而end
定义了迭代器在begin
停止迭代的位置的结尾。 begin
遍历字符串的原因是因为std::istream_iterator
的模板参数是std::string
:
std::istream_iterator<std::string> begin(std::cin), end;
//^^^^^^^^^^^
如果将其更改为char
,则begin
将迭代char
,这意味着以下程序将计算输入流中的字符数:
#include <iostream>
#include <algorithm>
#include <iterator>
int main() {
std::istream_iterator<char> begin(std::cin), end;
size_t count = std::distance(begin, end);
std::cout << count << std::endl;
return 0;
}
演示: http : //www.ideone.com/NH52y
同样,如果从<iterator>
头开始使用迭代器,并且从<algorithm>
头开始使用泛型函数,则可以做很多很酷的事情。
例如,假设我们要计算输入流中的行数。 那么,我们将对上述程序进行哪些更改以完成工作? 当我们想对字符计数时,我们将std::string
更改为char
的方式立即表明,现在我们需要将其更改为line
以便可以遍历line
(而不是char
)。
由于标准库中不存在任何line
类,因此我们必须自己定义一个, 但是有趣的是我们可以使用完整的工作代码将其保留为空 ,如下所示:
#include <iostream>
#include <algorithm>
#include <iterator>
#include <string>
struct line {}; //Interesting part!
std::istream& operator >>(std::istream & in, line &)
{
std::string s;
return std::getline(in, s);
}
int main() {
std::istream_iterator<line> begin(std::cin), end;
size_t count = std::distance(begin, end);
std::cout << count << std::endl;
return 0;
}
是的,除了line
,还必须为line
定义operator>>
。 由std::istream_terator<line>
类使用。
演示: http : //www.ideone.com/iKPA6
2. namespace std
是告诉编译器在哪里寻找在代码中引用的对象的方式。 因为不同的对象位于不同的名称空间“内部”,所以您必须告诉编译器它们的具体位置(aka std :: cin),或者为了方便起见告诉它将来使用的对象在哪里( using namespace std
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.