簡體   English   中英

該程序如何運作

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

在此代碼中,您將創建兩個迭代器beginend ,並將它們都傳遞給std::distance函數。 該函數計算beginend之間的距離。 距離不過是輸入流中字符串的數目,因為迭代器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

  1. Cin將捕獲輸入,直到空格為止。 循環的特定樣式將一直持續到找到文件結尾(EOF)或提供錯誤的輸入為止。 在我看來,該循環看起來並不像普通的C ++慣例,但在此處進行了描述。

2. namespace std是告訴編譯器在哪里尋找在代碼中引用的對象的方式。 因為不同的對象位於不同的名稱空間“內部”,所以您必須告訴編譯器它們的具體位置(aka std :: cin),或者為了方便起見告訴它將來使用的對象在哪里( using namespace std )。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM