Programing

한 줄씩 또는 전체 텍스트 파일을 한 번에 읽는 방법은 무엇입니까?

lottogame 2020. 10. 14. 07:19
반응형

한 줄씩 또는 전체 텍스트 파일을 한 번에 읽는 방법은 무엇입니까?


나는 파일을 소개하는 튜토리얼에 있습니다 (파일에서 읽고 쓰는 방법)

우선, 이것은 숙제가 아닙니다. 이것은 제가 찾고있는 일반적인 도움 일뿐입니다.

한 번에 한 단어 씩 읽는 방법을 알고 있지만 한 번에 한 줄씩 읽는 방법이나 전체 텍스트 파일을 읽는 방법을 모릅니다.

파일에 1000 단어가 포함되어 있으면 어떻게됩니까? 각 단어를 읽는 것은 실용적이지 않습니다.

(읽기)라는 내 텍스트 파일에는 다음이 포함됩니다.

나는 게임하는 것을 좋아한다 나는 읽는 것을 좋아한다 나는 책이 2 권있다

이것이 내가 지금까지 성취 한 것입니다.

#include <iostream>
#include <fstream>

using namespace std;
int main (){

  ifstream inFile;
  inFile.open("Read.txt");

  inFile >>

각 줄이나 각 단어를 따로 읽는 대신 한 번에 전체 파일을 읽을 수있는 방법이 있습니까?


다음을 사용할 수 있습니다 std::getline.

#include <fstream>
#include <string>

int main() 
{ 
    std::ifstream file("Read.txt");
    std::string str; 
    while (std::getline(file, str))
    {
        // Process str
    }
}

또한 명시 적으로 여는 것보다 생성자에서 파일 이름으로 파일 스트림을 구성하는 것이 더 낫다는 점에 유의하십시오 (닫을 때도 마찬가지입니다. 소멸자가 작업을 수행하도록하세요).

추가 문서 std::string::getline()CPP Reference 에서 읽을 수 있습니다 .

아마도 전체 텍스트 파일을 읽는 가장 쉬운 방법은 검색된 줄을 연결하는 것입니다.

std::ifstream file("Read.txt");
std::string str;
std::string file_contents;
while (std::getline(file, str))
{
  file_contents += str;
  file_contents.push_back('\n');
}  

나는 이것이 정말 정말 오래된 스레드라는 것을 알고 있지만 실제로 정말 간단한 다른 방법을 지적하고 싶습니다. 이것은 몇 가지 샘플 코드입니다.

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

int main() {

    ifstream file("filename.txt");
    string content;

    while(file >> content) {
        cout << content << ' ';
    }
    return 0;
}

I think you could use istream .read() function. You can just loop with reasonable chunk size and read directly to memory buffer, then append it to some sort of arbitrary memory container (such as std::vector). I could write an example, but I doubt you want a complete solution; please let me know if you shall need any additional information.


Well, to do this one can also use the freopen function provided in C++ - http://www.cplusplus.com/reference/cstdio/freopen/ and read the file line by line as follows -:

#include<cstdio>
#include<iostream>

using namespace std;

int main(){
   freopen("path to file", "rb", stdin);
   string line;
   while(getline(cin, line))
       cout << line << endl;
   return 0;
}

Another method that has not been mentioned yet is std::vector.

std::vector<std::string> line;

while(file >> mystr)
{
   line.push_back(mystr);
}

Then you can simply iterate over the vector and modify/extract what you need/

참고URL : https://stackoverflow.com/questions/13035674/how-to-read-line-by-line-or-a-whole-text-file-at-once

반응형