Ascending Descending order from a file using stack

Hello everyone! I'm new here with the programming and I can't find a solution here. I need to read the text file and then make it in ascending and descending order using 8 numbers I have in my text file. Also it needs to be something done with stack (which I hear first time). I do have this typed, but don't really know what to do, since ascending order is not working. The code in /* */ is working though, but I need to make the reading file correct. PLEASE help me through this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <iostream>
#include <iomanip>
#include <fstream>
#include <cstdlib>

using namespace std;

	int main()
	{
		int i, j, temp, a[100];
		/*cout<<"Type 10 numbers : \n";
		for(i=0;i<=10;i++)
		{
			cin>>a[i];
		}*/
		
		ofstream file;
		int value;
  		file.open ("example.txt");
    	        file >> value;
    	        file.close();
	
		for(i=0;i<=10;i++)
		{
			for(j=0;j<=10;j++)
			{
				if(a[j]>a[j+1])
				{
					temp=a[j];
					a[j]=a[j+1];
					a[j+1]=temp;
				}
			}
		}
		
		cout<<"\nDescending order: ";
		for(j=10;j>=0 ;j--)
		{
			cout<< " " << a[j];
		}
		

		
		cout<<"\nAscending order: ";
		for(j=10;j>=0 ;j--)
		{
			cout<< " " << a[j];
		}
		
	}

Hello elvizzz22,

Welcome to the forum.

First if you want to read a file it is "ifstream" not "ofstream". The "o" means output which does not allow for reading. For an input file it is best to check that the stream was opened and ready to use.

This may be more than you need, but I found it useful when first learn to deal with files.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
std::string iFileName{ "" };  // <--- Put file name here.

std::ifstream inFile;

inFile.open(iFileName);

if (inFile.is_open())
{
	std::cout << "\n File " << iFileName << " is open" << std::endl;
	std::this_thread::sleep_for(std::chrono::seconds(2));  // <--- Needs header files chrono" and "thread".
}
else
{
	std::cout << "\n File " << iFileName << " did not open" << std::endl;
	std::this_thread::sleep_for(std::chrono::seconds(3));  // <--- Needs header files chrono" and "thread".
	exit(1); // <--- No reason to continue. Any number > 0 indicates an error condition.
}

As you said and what you should do first is get the program to read the file even if it is just read and print get it working first then move on to use it to replace the "cin" part.

It is ALWAYS a good practice and programming to initialize your variables. If your compiler is using the C++11 standards or after the easiest way to initialize variables is with empty {}s, e.g., int num{};. This will initialize the variable to 0 (zero) or 0.0 for a double. A "char" will be initialized to "\0". "std::string"s are empty to start with and do not need to be initialized. Should you need to you can put a number between the {}s.You can also Initialize an array, e.g., int aNumbers[10]{};. This will initialize all elements of the array to 0 (zero). A use of
int aNumbers[10]{ 1 }; will initial the first element to "1" and the rest of the array to "0".. Following the "1" with ", 2 ..." will initialize the array with the numbers that you have used up to the entire array.

For the variables "i" and "j" it is best to define the these variables in the for loops that use them as in: for (int i = 0; ... and the same for "j". The only reason to define these variables out side of the for loop is if you need them somewhere after the for loop which is because of the scope of the for loop.

You may want to consider a second array. One for ascending and one for descending order.

I would also consider putting the sorting into a function.

For anything else I will have to give the program a run and see what happens.

Hope that helps,

Andy
Hello elvizzz22,

As I started working I realized that I have no idea what your input file looks like. Can you give me some idea of what the input file.

Andy
Basically what I need to do is by reading 8 numbers (2 lines, 4 numbers each) from file and make them by ascending and descending order using something called stack and put the result in the console.

Also, what do you mean by 2 arrays?
Hello elvizzz22,

What I have created for now will work. It is 10 numbers on one line.

Not sure what you are think of when you say "stack". It is more of a concept based off the "stack" the computer uses when the program runs and in this case "stack" is an area of memory to use.

The "stack" you are referring to is based on LIFO (Last In First Out) or you can think of it as you push something onto the top of the "stack" and retrieve what is on the top. To do what you want you could use an array, vector or some type of list. I am not sure if there is anything in the STL called "stack". The point is all in how you access what you create.

Once you have opened your file you will need to do something like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
std::size_t index{};

ifstream file;

file.open("example.txt");

if (!file.is_open())
{
	std::cout << "\n File " << "example.txt" << " did not open" << std::endl;
	std::this_thread::sleep_for(std::chrono::seconds(3));  // <--- Needs header files chrono" and "thread".
	exit(1);  // <--- No reason to continue.
}

while (file >> value)
	a[index++] = value;

//  Or simply. Notice the ; at the end.
//while (file >> a[index++]);

file.close();

Not only is index used for the subscript of the array, but it also becomes a variable to keep track of how many elements of the array are used.

Once you fill the array I had to change the for sort to:
1
2
3
4
5
6
7
8
9
10
11
12
for (int i = 0; i < index; i++)
{
	for (int j = 0; j < index - 1; j++)
	{
		if (a[j] > a[j + 1])
		{
			temp = a[j];
			a[j] = a[j + 1];
			a[j + 1] = temp;
		}
	}
}

Notice how I used "index" in the for conditions. This way it will not matter how many elements are used it will always work.

In the inner for loop I used "index - 1" because "a[j + 1]" will put you beyond the usable elements of the array, i.e., one past what you can use.

The next two for loops are good for printing out the array and both need fixed to work correctly, but both have nothing to do with a "stack".

Some of the program is worth keeping, but overall it needs to be reworked to be used more like a "stack". I would use a vector over the array. Technically backwards from what you would think of when you say "stack", but it can work the same way.

If this is homework post the requirements so I do not point you in the wrong direction.

I can fix what you have, but what you have is not what you want.

Hope that helps,

Andy

Edit:

Two arrays as in ascending[MAXSIZE] and descending[MAXSIZE] and I would define "MAXSIZE" as constexpr std::size_t MAXSIZE{ 100 };. I also said that based on the code I see before I had a better understanding of what you want.
Last edited on
I don't really need to check if file has opened correctly or not. There are no typed requirements. All we learnt was matrix and some basic stuff. What I have now is this, but in console it gives the first number in my text file. I think I need to change 13th-17th line.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <iostream>
#include <iomanip>
#include <fstream>
#include <cstdlib>

using namespace std;

int main()
{
	int i, j, temp, a[100];
	
		
	ifstream file;
	int value;
	file.open ("Sav1skaiciai.txt");
   	file >> value;
   	file.close();
  	
		
	for (int i = 0; i < index; i++)
	{
		for (int j = 0; j < index - 1; j++)
		{
			if (a[j] > a[j + 1])
			{
				temp = a[j];
				a[j] = a[j + 1];
				a[j + 1] = temp;
			}
		}
	}	
		
		
	cout<<"\nMazejimo tvarka: ";
	for(j=9;j>=0 ;j--)
	{
		cout<< " " << value;
	}
		

		
	cout<<"\nDidejimo tvarka: ";
	for(j=9;j>=0 ;j--)
	{
		cout<< " " << value;
	}
		
}
Hello elvizzz22,

I don't really need to check if file has opened correctly or not.
Guess that is the difference between a good programmer and an average programmer.

There are no typed requirements.
Get use to it. Not every program will tell you every step that you will need to do. It is up to you to fill in the details.

What I have now is this, but in console it gives the first number in my text file.
Because that is all you tell the program to give you. If I follow what you said there are eight numbers in the file, but you only read one. And you have created an array, but you put nothing in it. As of now with your program the array contains garbage. That means the program has set aside memory on the "stack" when the program compiles. When the program runs whatever is in the memory at that time the program runs is interpreted as an int and is an unknown number and could have unexpected results.

To your program:

Line 10. The variables "i" and "j" are no longer needed. The other variables including the array need to be initialized.

Line 14. I would move up to line 11, but that is just me. I like to keep all my variable definitions in one place. Also "value" should be initialized.

Lines 13 and 15 are OK, but after line 15 you should check that the file stream is opened and working.

Line 16. Only reads one value from the file. Maybe? That still leaves 7 other numbers to be read.

Line 17. Is OK here, but I like to put it at the end just before the return 0; that you do not have.

Line 20 and 22. A better start. In the first part you have defined "i" and "j" as you should and the third part is OK. In the middle part you have a problem. "index" is never defined and before line 20 it is never given any value. So even if "ndex" was defined it might have value of "-858993460" in which case "i" would never be less than "index" and the for loops would never start.

The sort works not that you should be sorting anything if this is to be a "stack".

The remaining two for loops are still wrong.

Hope that helps,

Andy
Handy Andy wrote:
The "stack" you are referring to is based on LIFO (Last In First Out) or you can think of it as you push something onto the top of the "stack" and retrieve what is on the top. To do what you want you could use an array, vector or some type of list. I am not sure if there is anything in the STL called "stack".
1
2
#include <stack>  // LIFO
#include <queue>  // FIFO 

Lot of awesome STL containers out there. Tbh, if you can think if of it, it probably exists.
Last edited on
@icy1,

Thanks for the tip. Not something I have used very often.

@elvizzz22,

In regards to checking if the file is opened you made the statement There are no typed requirements.Again I ask what are the requirements. You are saying one thing and the program is saying something different. I need to know what you need to do with this program before we can figure out what to do with the program.

Andy
Last edited on
Topic archived. No new replies allowed.