2014-11-03 42 views
0

我嘗試創建一個C++程序,讀取一個文件,並計算以下具體準則的文件中的行數,字數和字符數:的I/C++文件的Ø

  • 用途的std ::函數getline( )逐行讀取輸入。
  • 統計所有字符,包括分隔行的換行符。 cin.eof()的返回值可用於確定一行是否被換行符終止。
  • 每個單詞由空格或製表符分隔(「\ t」)。
  • first_of()和first_not_of()查找下一個單詞的開始。

唯一的問題是,我不知道如何做到這一點。但是,我設法使用getline()來計算行數。但之後,不知道。如果你能指出我正確的方向,並告訴我如何做到這一點(我是一個視覺學習者),我將不勝感激!

繼承人我得到了什麼至今(不太多,我知道):

#include <iostream> 
#include <fstream> 
#include <string> 
using namespace std; 

int main() { 
    string line; 
    int numLines = 0; 
    ifstream file ("horton.txt"); 
    if (file.is_open()){ 
     while (getline (file,line)){ 
      ++numLines; 
     } 
    file.close(); 
    cout <<numLines<<endl; 
    } 
    else cout << "Unable to open file"; 
} 
+0

有人嗎?我在這裏需要一些幫助,因爲我畫空白。 – a22asin 2014-11-03 22:57:16

+0

那麼,如何知道一個字符串是否包含空格或製表符等字符? – 2014-11-03 23:05:13

+0

這個任務,假設有。 – a22asin 2014-11-03 23:08:39

回答

0

讓我們從方案中刪除的文件,並尋找在已知的一句話工作。

#include <string> 
#include <stdio> 

int main(void) 
{ 
    const std::string test_data = "I do not like green eggs and ham, Sam I am."; 

    return 0; 
} 

根據您的要求,std::string::find_first_of可用於查找單詞。讓我們添加包含單詞分隔字符串,並調用它white_space

#include <string> 
#include <stdio> 

int main(void) 
{ 
    const std::string test_data = "I do not like green eggs and ham, Sam I am."; 
    const std::string white_space = " \t"; // Space and tab. 

    return 0; 
} 

我們可以搜索test_data的白色空間中第一次出現:

std::string::size_t position = test_data.find_first_of(white_space); 

該語句將設置變量position到第一個空白字符在文本字符串中的位置。在我們的例子中,它應該是1,因爲字母'I'佔據了位置0.

有了更多想法,我們可以增加空間位置並使用find_first_not_of方法獲得下一個位置空間。如果我們保存以前的位置,我們可以提取剛剛跳過的單詞。

您或許可以計算空白空間實例的數量。

通過使用調試器,我們一步一步(執行)一條語句,看看position變量在循環中如何變化。如果您對調試器有異議,您可以使用將變量名稱和它們的值打印到控制檯的古老藝術。

+0

好的,我將如何使find_first_of從最後一個位置find_first_not_of開始設置爲?另外,我將如何檢查線是否完成,如果線只是空白(沒有字符)? – a22asin 2014-11-03 23:36:13

+0

我不知道,可能通過查看我的語言文本或cppreference.com,並注意到std :: string方法'find_first_not_of'有一個可選參數作爲開始位置。 Ooooh,有很多方法來檢測空字符串:'(test_data.length()== 0),(test_data.size()== 0),(test_data.empty())'。閱讀參考手冊可以找到很多東西。 – 2014-11-03 23:46:19

+0

我聽說這些搜索函數在到達或超出字符串末尾時會返回一個值。 http://en.cppreference.com/w/cpp/string/basic_string/npos – 2014-11-03 23:47:29