2015-12-03 35 views
1

我有這樣的一個下面添加一個整數一個struct

「不兼容的類型中的intint [10000]分配」

我不明白什麼是錯的錯誤。這裏是我的代碼:

#include<fstream> 
#include<string> 
#include<vector> 
#include<algorithm> 

using namespace std; 

struct words{ 

    string lexis; 
    int sizes[10000]; 

} a[10000]; 

bool s(const words& a,const words& b); 

//========================================== 
int main() { 
    int i,x; 
    string word; 

    //input-output with files 
    ifstream cin("wordin.txt"); 
    ofstream cout("wordout.txt"); 

    i = 0; 

    //reading until the end of the file 
    while(!cin.eof()){ 
     cin >> word; 

     x = word.size(); 

     a[i].sizes = x; //the problem is here 

     a[i].lexis = word; 
     i++; 
    } 

} 

我真的很感激,如果有人幫助我。 :) 感謝

+2

做**不**使用'cin.eof()'作爲循環讀取輸入的主要條件。另外,使用'while(cin >> word){...}' –

+4

'a [i] .sizes'產生一個int(&)[10000]',檢查任何輸入_after_讀和_before_。你可以給'a [i] .sizes [j]'分配一個'int'。 –

+2

你確定你想要10000個10000個數組的數組嗎? IT看起來你的結構在使用方面沒有很好的定義。不要在C++中使用原始數組,請使用更方便的向量(動態數組)。 –

回答

1

避免使用變量具有相同標準庫的名字,你的情況重命名兩種文件流cincout,例如,my_cinmy_cout

如果你想讀取多個string S或int的使用std::vector代替陣列,即,而不是你的struct words你可以使用:

vector<string> words; 

,然後從文件中讀取,你可以這樣做:

// attach stream to file 
ifstream my_cin("wordin.txt"); 

// check if successfully opened 
if (!my_cin) cerr << "Can't open input file!\n"; 

// read file line by line 
string line; 
while (getline(my_cin, line)) { 

    // extract every word from a line 
    stringstream ss(line); 
    string word; 
    while (ss >> word) { 

     // save word in vector 
     words.push_back(word); 
    } 
}