프로그래밍 언어/C++
C ++에서 ifstream을 사용하여 한 줄씩 파일 읽기
Rateye
2021. 6. 9. 10:33
728x90
반응형
질문 : C ++에서 ifstream을 사용하여 한 줄씩 파일 읽기
file.txt의 내용은 다음과 같습니다.
5 3
6 4
7 1
10 5
11 6
12 3
12 4
여기서 5 3
은 좌표 쌍입니다. C ++에서이 데이터를 한 줄씩 어떻게 처리합니까?
첫 번째 줄을 얻을 수 있지만 파일의 다음 줄은 어떻게 얻습니까?
ifstream myfile;
myfile.open ("file.txt");
답변
먼저 ifstream
만듭니다.
#include <fstream>
std::ifstream infile("thefile.txt");
두 가지 표준 방법은 다음과 같습니다.
- 모든 줄이 두 개의 숫자로 구성되어 있고 토큰별로 읽는다고 가정합니다.
int a, b; while (infile >> a >> b) { // process pair (a,b) }
- 문자열 스트림을 사용하는 라인 기반 구문 분석 :
#include <sstream> #include <string> std::string line; while (std::getline(infile, line)) { std::istringstream iss(line); int a, b; if (!(iss >> a >> b)) { break; } // error // process pair (a,b) }
int a, b; while (infile >> a >> b) { // process pair (a,b) }
모든 줄이 두 개의 숫자로 구성되어 있고 토큰별로 읽는다고 가정합니다.
int a, b;
while (infile >> a >> b)
{
// process pair (a,b)
}
#include <sstream> #include <string> std::string line; while (std::getline(infile, line)) { std::istringstream iss(line); int a, b; if (!(iss >> a >> b)) { break; } // error // process pair (a,b) }
문자열 스트림을 사용하는 라인 기반 구문 분석 :
#include <sstream>
#include <string>
std::string line;
while (std::getline(infile, line))
{
std::istringstream iss(line);
int a, b;
if (!(iss >> a >> b)) { break; } // error
// process pair (a,b)
}
(1)과 (2)를 섞어서는 안됩니다. 토큰 기반 파싱은 줄 바꿈을 잡아 먹지 않기 때문에 토큰 기반 추출 후 getline()
이미 줄의 끝입니다.
출처 : https://stackoverflow.com/questions/7868936/read-file-line-by-line-using-ifstream-in-c
728x90
반응형