2012-04-19 17 views
0

이렇게 간단한 문제처럼 보입니다. 그러나 나는 그것에 어려움을 겪고 있습니다. 큰 파일을 가지고 있는데, 그 파일에있는 모든 문자를 char 배열에 넣고 싶습니다. 내 문제는 내가 어떻게 줄 바꿈과 공백을 다루는 지 모르겠다. 파일을보고 모든 문자를 잡고 줄 바꿈을 건너 뛰고 배열에 넣는 방법이 있습니까?C++ : 줄 바꿈과 공백을 무시하고 파일의 모든 문자를 잡으십시오.

예, Google에서 검색했지만 행운이 없습니다.

+0

게놈에서 읽는 것 같아요? – cmo

답변

1

다음은 자발적으로 C에서 어떻게 수행되는지입니다. C++ 인터페이스를 사용하여이 작업을 수행 할 수 있다고 확신하지만 C 라이브러리는 C++의 일부이기도합니다.

#include <stdio.h> 
#include <ctype.h> 

FILE *f = fopen ("filename", "r"); 
if (!f) 
    error ... 

char array [BIGENOUGH]; 
int index = 0; 
while (!feof (f)) 
{ 
    char c = fgetc (f); 
    if (!isspace (c)) 
     array [index++] = c; 
} 
fclose (f): 
+0

배열의 끝에있는 EOF를 삭제해야한다고 생각합니다. –

+0

완벽하게 작동했습니다. 고마워요. 나는 fstream 라이브러리를 사용하려고 시도했다. 이것은 훨씬 쉽습니다. – LiverpoolFTW

0

선호하는 방법은 표준 라이브러리 문자열을 사용하는 것입니다. 문자열에서 공백을 제거하는 예 here. 파일을 한 줄씩 읽는 방법 here.

예제 코드 :

fstream file; 
file.open("test.txt",ios::in); 
while (!file.eof()) { 
    string str; 
    file >> str; 

    remove_if(str.begin(), str.end(), isspace); 
    str.erase(remove_if(str.begin(), str.end(), isspace), str.end()); 
    //save str here 
} 

file.close(); 

remove_if 샘플 구현 :

template<typename T, typename P> 
T remove_if(T beg, T end, P pred) 
{ 
    T dest = beg; 
    for (T itr = beg;itr != end; ++itr) 
     if (!pred(*itr)) 
      *(dest++) = *itr; 
    return dest; 
} 

이 코드는 테스트되지 않은 것입니다.

0

fgets은 줄 바꿈까지 읽을 수 있습니다 (대상 버퍼에 줄 바꿈이 계속 남아 있으므로 '\ 0'으로 겹쳐 쓰십시오).
한 줄씩 파일을 읽고 출력 할 때마다 이전 출력과 연결하십시오.

1

C++에서 원하는 것을 수행하는 핵심은 형식화 된 입력 작업을 이용하는 것입니다. 공백을 무시하고 싶습니다. 형식화 된 입력 메소드는이를 정확히 수행합니다.

#include <fstream> 
#include <iostream> 

int main() { 
    std::ifstream inFile("input.txt"); 

    char c; 
    std::string result; 
    while(inFile >> c) 
    result.push_back(c); 

    std::cout << result; 
} 

나는 표준 알고리즘은 루프를 손으로 만들어진 선호 : 여기

는 정규 C++ 입력 루프를 사용하는 하나의 방법이다. std::copy을 사용하여 C++에서이를 수행하는 한 가지 방법이 있습니다. 이 방법과 첫 번째 방법은 거의 동일합니다.

#include <vector> 
#include <fstream> 
#include <iostream> 
#include <iterator> 
#include <algorithm> 

int main() { 
    std::ifstream inFile("input.txt"); 
    std::string result; 
    std::copy(std::istream_iterator<char>(inFile), 
      std::istream_iterator<char>(), 
      std::back_inserter(result)); 
    std::cout << result; 
} 

또 다른 방법으로 이번은 std::accumulate입니다. std::accumulatepush_back 대신 operator+을 사용하므로 한 번에 string의 파일을 읽을 수 있습니다.

#include <vector> 
#include <fstream> 
#include <numeric> 
#include <iostream> 
#include <iterator> 
#include <algorithm> 

int main() { 
    std::ifstream inFile("input.txt"); 
    std::string result = 
    std::accumulate(
     std::istream_iterator<std::string>(inFile), 
     std::istream_iterator<std::string>(), 
     std::string()); 
    std::cout << result; 
} 
관련 문제