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

不幸的是,我不允许使用此代码的向量。有什么不同的建议? –