[英]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.