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;
}