2017-10-06 228 views
1

我只是對C++從文本文件中讀取到一個數組

我想讀的文本文件(最多1024個字)到一個數組一個初學者,我需要忽略所有單個字符的話。你們能幫我丟棄單個字符的單詞,以避免符號,特殊字符。

這是我的代碼:

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

const int SIZE = 1024; 

void showArray(string names[], int SIZE){ 
    cout << "Unsorted words: " << endl; 
    for (int i = 0; i < SIZE; i++){ 
     cout << names[i] << " "; 
     cout << endl; 
    } 
    cout << endl; 
} 
int main() 
{ 
    int count = 0; 
    string names[SIZE]; 

    // Ask the user to input the file name 
    cout << "Please enter the file name: "; 
    string fileName; 
    getline(cin, fileName); 
    ifstream inputFile; 
    inputFile.open(fileName); 

    // If the file name cannot open 
    if (!inputFile){ 
     cout << "ERROR opening file!" << endl; 
     exit(1); 
    } 

    // sort the text file into array 
    while (count < SIZE) 
    { 
     inputFile >> names[count]; 
     if (names[count].length() == 1); 
     else 
     { 
      count++; 
     } 
    } 
    showArray(names, SIZE); // This function will show the array on screen 
    system("PAUSE"); 
    return 0; 
} 

回答

1

如果更改namesstd::vector,那麼你可以使用push_back填充它。你可以這樣填寫names

for (count = 0; count < SIZE; count++) 
{ 
    std::string next; 
    inputFile >> next; 
    if (next.length() > 1); 
    { 
     names.push_back(next); 
    } 
} 

另外,您可以填寫所有的話到names,然後利用Erase–remove idiom

std::copy(std::istream_iterator<std::string>(inputFile), 
      std::istream_iterator<std::string>(), 
      std::back_inserter<std::vector<std::string>>(names)); 

names.erase(std::remove(names.begin(), names.end(), 
       [](const std::string& x){return x.length() == 1;}), names.end()); 
+0

不幸的是,我不允許使用此代碼的向量。有什麼不同的建議? –