아하 로고
검색 이미지
생활꿀팁 이미지
생활꿀팁생활
생활꿀팁 이미지
생활꿀팁생활
매끈한천인조92
매끈한천인조9221.04.13

C플플 외부 텍스트파일 정렬해서 출력하는법

C++에서 ifstream(file.txt)로 파일 안에있는 숫자들을 가져오려는데(정수말고 소수도 있습니다) 이때 sort함수 없이 오름차순으로 정렬시키려면 어떤식으로 프로그래밍 해야 할까요? ㅠㅠ

55글자 더 채워주세요.
답변의 개수1개의 답변이 있어요!
  • 탈퇴한 사용자
    탈퇴한 사용자21.04.15

    file.txt 에 숫자만 포함하고 있다고 가정하고 답변드립니다.

    sort 함수를 쓰지 않고 해야 한다고 해서 자료구조중 하나인 set 을 사용하여 스트림에서 데이터를 읽어서 저장했다가 화면에 출력하도록 하였습니다.

    파일에서 읽으면 숫자의 형태라고 해도 결국은 문자형태이기 때문에 atof로 실수형으로 변환을 하는 과정을 거쳤습니다.

    file.txt 의 내용과 프로그래밍 실행

    코드

    #include <iostream> #include <fstream> #include <set> #include <stdlib.h> int main(int argc, const char * argv[]) { std::ifstream input("file.txt"); ///< open input file if (!input.is_open()) { std::cout << "Error opening file!" << std::endl; return 1; } std::set<double> sortedNumbers; std::string value; while (std::getline(input, value)) { double number = atof(value.c_str()); sortedNumbers.insert(number); } for (const auto& n : sortedNumbers) { std::cout << n << std::endl; } return 0; }