2017-10-06 13 views
1

저는 C++의 초보자입니다.텍스트 파일에서 배열로 읽기

텍스트 파일 (최대 1024 단어)을 배열로 읽고 모든 단일 문자 단어를 무시해야합니다. 당신은 기호, 특수 문자를 피하기 위해 하나의 문자 인 단어를 버리도록 도와 줄 수 있습니까?

이 내 코드입니다 : 당신이 std::vectornames을 변경하는 경우

#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

, 당신은 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를 사용할 수 없습니다. 다른 제안? –

관련 문제