Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way to refactore this code and make it work?

I’m trying to create a function and link it to a header file and call the function to my main.cpp.
This is the code from one function which I’ll be calling in my main.cpp file.
I’m trying to create a sort function that determines whether the integers in the file are sorted in order or not.

The file I’ll be reading from can both be sorted and not sorted and output for the user the results, depending on the outcome of the file.
Hopefully, I’m explaining in a clear! :S

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
#include "SortingFunc1.h"

int file_sort_checker() {
  int nums;
  std::string in_file_name;
  std::ifstream resultat;
  resultat.open("A");
  resultat >> nums;

  while (resultat.eof()) {
    bool resultat = std::is_sorted(in_file_name.begin(), in_file_name.end());

    if (resultat)
      std::cout << "Filen är sorterad!" << nums << std::endl;
    else {
      std::cout << "Filen är inte sorterad!" << nums << std::endl;
    }
    resultat >> nums;
  }

  resultat.close();
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Here is a code fragment that checks if numbers in a file are sorted, ascending:

std::ifstream resultant("A");
int previous_number;
int number;
resultant >> previous_number;
bool is_sorted = true;
while (resultant >> number)
{
    if (number < previous_number)
    {
        std::cout << "File not sorted\n";
        is_sorted = false;
        break;
    }
    previous_number = number;
}

The previous number is primed by reading the first number into the variable.
The loop then compares the next number read to the previous. The loop will continue if the next number is greater than or equal to the previous number.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading