2017-10-06 41 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

あなたはstd::vectornamesを変更する場合は、あなたが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

残念ながら、このコードではvectorを使用できません。任意の異なる提案? –

関連する問題