2015-11-13 70 views
0

我想讀取一個外部文件,並將文件中的所有字符串放入字符串類型的數組中。如何將外部文件中的值放入數組中?

這是我的主要功能:

#include <iostream> 
#include "ReadWords.h" 
#include "Writer.h" 
#include <cctype> 
#include <string> 

using namespace std; 

int main() { 

    int count; 
    const int size = 10; 
    string word_search[size]; 
    string word; 

    cout << "Please enter a filename: " << flush; 
    char filename[30]; 
    cin >> filename; 

    ReadWords reader(filename); 
    while (reader.isNextWord()){ 
     count = count + 1; 
     reader.getNextWord(); 

    } 

    cout << "Please enter the name of the file with the search words: " << flush; 

    char filename1[30]; 
    cin >> filename1; 

    ReadWords reader1(filename1); 
    while (reader1.isNextWord()) { 

這就是我想要的字符串存儲在名爲word_search一個數組,然而,這不是目前的工作。如何將字符串存儲在數組中?

 for(int i = 0; i < size; i++){ 
      word_search[i] = word; 

     } 
    } 

這是我在哪裏打印數組的內容,看看我是否成功。

cout << word_search << endl; 



    return 0; 
} 

這是所有方法中有一個名爲ReadWords.cpp一個單獨的文件被宣佈:

#include "ReadWords.h" 
#include <cstring> 
#include <iostream> 
using namespace std; 

void ReadWords::close(){ 
    wordfile.close(); 

} 

ReadWords::ReadWords(const char *filename) { 
    //storing user input to use as the filename 

     //string filename; 

     wordfile.open(filename); 

     if (!wordfile) { 
      cout << "could not open " << filename << endl; 
      exit(1); 
     } 
} 

string ReadWords::getNextWord() { 

    string n; 


    if(isNextWord()){ 
     wordfile >> n; 
     //cout << n << endl; 

     int len = n.length(); 
     for(int i = 0; i < len ; i++) { 

      if (ispunct(n[i])) 
        { 
         n.erase(i--, 1); 
         len = n.length(); 
        } 
     } 
      cout << n << endl; 
     return n; 

    } 
} 

bool ReadWords::isNextWord() { 

     if (wordfile.eof()) { 
      return false; 
     } 
     return true; 
} 
+0

問題是什麼?如果設置正確,for循環可以很好地工作。 –

+0

我的第一個猜測告訴我你要替換'word_search [i] = word; '''''word_search.push_back(word);' –

+0

@CaptainGiraffe:啊,是那個着名的函數'((std :: string)[10]):: push_back'。 –

回答

0

你可能是指

size_t count = 0; 
    while (reader.isNextWord()){ 
     word_search[count] = reader.getNextWord(); 
     ++count; 
    } 

而且,考慮使用的std ::矢量而不是一個數組。另外,變量「單詞」未被使用。 要打印內容使用

for (size_t i = 0; i < size; ++i) 
     cout << word_search[i] << endl; 
相關問題