2016-11-11 37 views
-1

這個程序應該從由用戶提供的文本文件讀出的段,然後將每個線存儲在參差不齊的字符數組和計算單詞和線的總數量的行然後顯示結果。如何計算單詞和被輸入作爲一個CString陣列

我想不通爲什麼行的數量不斷給我的3 爲什麼單詞的數量總是缺少2個字的結果。

請幫助,並記住,我不是專業的,剛開始學習C++最近。

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

int main() 
{ 
    ifstream infile;//declarations 
    char filename[45]; 
    char **data = 0; 
    char **temp = 0; 
    char *str = 0; 
    char buffer[500], c; 
    int numoflines = 0, numofwords = 0; 

    cout << "Please enter filename: ";//prompt user to enter filename 
    cin >> filename; 

    infile.open(filename);//open file 

    if (!infile)//check if file was successfully opened 
    { 
     cout << "File was not successfully opened" << endl << endl;//display error message 
     return 0; 
    } //end of if 

    data = new char*[numoflines]; 

    while (!infile.eof()) 
    { 
     temp = new char*[numoflines + 1]; 

     for (int i = 0; i < numoflines; i++) 
     { 
      infile.getline(buffer, 500);//read line 
      for (int i = 0; i < strlen(buffer); i++)//count number of words in line 
      { 
       c = buffer[i]; 
       if (isspace(c)) 
        numofwords++; 
      } 
      str = new char[strlen(buffer) + 1];//allocate a dynamic array 
      strcpy(str, buffer); 
      data[i] = str; 
      temp[i] = data[i]; 
     }//end of for 

     infile.getline(buffer, 500); 
     for (int i = 0; i < strlen(buffer); i++)//count number of words in line 
     { 
      c = buffer[i]; 
      if (isspace(c)) 
       numofwords++; 
     } 

     temp[numoflines] = new char[strlen(buffer) + 1]; 
     strcpy(temp[numoflines], buffer); 

     delete[] data; 
     data = temp; 
     numoflines++; 
    } 

    cout << "Number of words: " << numofwords << endl; 
    cout << "Number of lines: " << numoflines << endl; 

    return 0; 
} 
+0

對於'ifstream :: getLine',默認分隔符是'\ n'。我猜你的文本包含3段,它只包含3個'\ n'字符,這就是爲什麼你得到3作爲行數。 – sanastasiadis

+0

對於單詞數量,我猜問題是你檢查了空格字符。也許檢查空間「或」時期「。會更好。 – sanastasiadis

+0

考慮「這個字符串」。它有兩個詞,但有很多空格。還要考慮「這個字符串」 - 它有兩個字,只有一個空格。最後「這是怎麼回事」?這是一個字還是三個字? (哦,不要忘記「」 - 這是零字)。 –

回答

0

行數的概念只是一個觀看概念。它沒有被編碼到文件中。下面的一個段落,可以顯示在一行或16行,這取決於編輯器窗口的大小:

enter image description here

enter image description here

如果要指定窗口的字符寬度,線可能可以從中計算出來,但按原樣,段落和wordcount的效果與您將要做的一樣好。並且獲得成功打開ifstream infile那是相當簡單的獲得:

auto numoflines = 0; 
auto numofwords = 0; 
string paragraph; 

while(getline(infile, paragraph)) { 
    numofwords += distance(istream_iterator<string>(istringstream(paragraph)), istream_iterator<string>()); 
    ++numoflines; 
} 

cout << "Number of words: " << numofwords << "\nNumber of lines: " << numoflines << endl; 

注:

的Visual Studio支持的istringstream內嵌建設,所以如果你不使用你需要構建在一條單獨的線上。

相關問題