Home > Software design >  Is there a way to refactore this code and make it work?
Is there a way to refactore this code and make it work?

Time:12-03

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

CodePudding user response:

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.

  • Related