2013-07-13 100 views
0

我不知道如何閱讀幾個段落,而不是將每個單詞放在結構中,而不是計算有多少獨特單詞。字符串問題C++

我知道如何讀取數據只是沒有從一個字符串中傳遞一個字。正如我前面所說的在幾段中讀

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


struct words 
{ 
    char unique[21]; 
    int count; 
} test; 

void inputFile (words essay[100]); 
int search (int index, int subscript, int integer,words essay[100]); 

int main() 
{ 
    words essay[100]; 
    inputFile (&test); 

    cout << essay[0].unique<<test.count; 
    return 0; 
} 


void inputFile (words essay[100]) 
{ 
    char fileName[81]; 
    char copyName[81]; 
    cout << "What is the name of the input file? \n"; 
    cin >> fileName; 


    ifstream infile; 
    ofstream outfile; 
    int count = 0; 
    char line [81]; 
    int ch; 
    infile.open(fileName); 
    outfile.open(copyName); 

    while ((ch = infile.peek()) != EOF) 
    { // while not end of file 
     infile.getline (line[81].unique, 81); 
     cout << "Copying: " << line << endl; 


     count++; 
     outfile << essay << endl; 
    } 

    cout << "There were " << count << " lines copied\n"; 
    cout << endl; 
    // close both files 
    infile.close(); 
    outfile.close(); 
}; 


/*int search (int index, int subscript, int integer, struct words essay[100]) 
{ 
    string key; 
    key = test.unique; 
    int n; 
    n = test.count; 
    int i; 
    i = 0; 
    while (i < n && essay[i] != key) 
    i++; 
    if (i == n) 
    { 
     i = -1; 
    } 
    return i; 
    };*/ 
+0

是否會編譯代碼?在第一眼看來它不應該... ...僅供參考,在文本中計算單詞是一件容易的事情,很多答案都描述瞭如何做到這一點。 http://stackoverflow.com/questions/16867944/counting-occurrences-of-each-word-in-a-text-file – alexbuisson

+0

你不必偷看。只需寫'while(infile.getline(...)){...}'。順便說一句'[81] .unique'沒有任何意義;你想在那裏做什麼?無論如何,你應該將'line'定義爲'std :: string',並使用'std :: getline(infile,line)'而不是'infile.getline(...)'。 –

+0

爲什麼如果你明確地談論C++字符串,包括cstring?使用'std :: string'(標題) – Manu343726

回答

0

這是一個部分的答案,主要側重於清理流讀取邏輯。我無法弄清楚你在做什麼,並且有足夠的清晰度來提供更多的幫助。 (例如,你爲什麼輸出essayoutfile而沒有放入任何東西。)

void inputFile (words essay[100]) 
{ 
    std::string fileName, copyName; 
    cout << "What is the name of the input file?\n"; 
    cin >> fileName; 
    // I assume you get copyName here… 
    // Though fileName and copyName really should be parameters 
    // passed in from `main()`. 

    ifstream infile(fileName); 
    ofstream outfile(copyName); 
    std::string line; 
    int count = 0; 
    while (getline(infile, line)) 
    { 
     cout << "Copying: " << line << endl; 
     count++; 
     outfile << essay << endl; // No idea what you're doing here. 
    } 

    cout << "There were " << count << " lines copied\n"; 
}; 
+0

這只是應該輸出什麼是「複製」,我可以做到這一點,我只是不明白如何採取我複製(輸入),而不是把每個單詞的結構和單詞數獨特的。 – user2275639

+0

我知道我需要一個for循環,我只是不知道如何讓它分離空白區域,所以你在結構中有每個單詞。 – user2275639