2011-10-25 75 views
1

這是我的第一個C++程序。它打印輸入中的字數。這個程序是如何工作的

我的第一個問題,它是如何進入循環並添加到計數?每次我輸入空格字符嗎?如果是這樣,它是如何知道我在努力數字?

using namespace std; 

int main() { 
    int count; 
    string s; 
    count = 0; 
    while (cin >> s) 
     count++; 
    cout << count << '\n'; 
    return 0; 
} 

我的第二個問題。有人可以向我解釋什麼名字空間標準對於一個起居者來說意味着什麼?

回答

2
  1. CIN將捕捉到的輸入空間,是的。直到找到文件結尾(EOF)或直到提供錯誤輸入爲止,循環的具體樣式將一直持續。該循環看起來並不像我常見的C++練習,但它的描述爲here

2. namespace std是如何讓編譯器知道在代碼中查找引用的對象的位置。因爲不同的對象在不同的​​命名空間「內部」,所以你必須告訴編譯器他們是在哪裏(或者std :: cin),或者爲了方便將它用在將來使用的對象上(爲using namespace std)。

+0

我發現它實際上是兩種常見的方式。一個是如他所示,另一個如果遇到EOF或任何其他錯誤,就會慘敗。 –

7

當你做cin >>字符串。你會讀一個字,並把它放在字符串中。是的,它將讀取char字符直到達到分隔符。

Std表示標準。標準C++庫位於std名稱空間內。你可以重寫或代碼,而無需使用空間std的

int main() { 
    int count; 
    std::string s; 
    count = 0; 
    while (std::cin >> s) 
     count++; 
    std::cout << count << '\n'; 
    return 0; 
} 

我勸阻說新手使用空間std語句,因爲它是很難明白是怎麼回事上使用。

+0

這和'set'是一個不幸常用的名字。 –

2

在您的代碼中,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對來自輸入流的字符串進行迭代,並且end定義迭代器的結束,其中begin停止迭代。之所以begin遍歷字符串是因爲模板參數std::istream_iteratorstd::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一樣,您也必須定義operator>>以獲得line。它由std::istream_terator<line>類使用。

演示:http://www.ideone.com/iKPA6