I have the F file which has these numbers:
-9
-8
-7
-6
-5
-4
-3
-2
-1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
I have to make these numbers in a descending order and give them to the G file. What i get in the G file is :
9
8
7
6
5
4
3
2
1
1
2
3
4
5
6
7
8
9
10
11
21
31
41
51
61
Pls help me on the code how do i do this. Thank you in advance <3
#include <iostream>
#include <string>
//#include <stdio.h> // <--- Not used or needed.
//#include <cstring> // <--- Not used or needed.
#include <fstream>
#include <algorithm>
int main()
{
int skaitli, it{}; // <--- ALWAYS initialize all your variables.
std::string rinda; // <--- Does not need initialized. Empty when defined.
std::ifstream F("F.txt"); // <--- Use a better file name than "F". Maybe "inFile".
// <--- How do you know it is open and usable? Need to check.
std::ofstream G; // <--- Should do this the same as you did the "ifstream". Use a better file name than "G". Maybe "outFile".
G.open("G.txt");
// <--- How do you know it is open and usable? Need to check.
while (std::getline(F, rinda))
{
std::sort(std::begin(rinda), std::end(rinda), std::greater<int>()); // <--- Sort after the while loop.
try
{
skaitli = std::stoi(rinda);
}
catch (std::invalid_argument& e)
{
std::cout << "Nav skaitlis " << it << '\n';
continue;
}
G << skaitli << '\n';
it++;
}
G.close(); // <--- Not required as the dtor will close the file when the function looses scope.
return 0; // <--- Not required, but makes a good break point for testing.
}
This is untested at the moment. I will test it later.
1. Read all values into container
2. Sort the container
3. Write values from container
(With devious "sort ascending, write reverse".)
The OP logic is quite different:
for each line in input
read line
reorder characters in line
write line to output
Therefore, line k of input is always line k of output. No reordering of lines is done.
Furthermore, you read line as text, sort characters in that text, then convert to number and finally write the number.
If line has "-4275", then the text after sort is "7542-" and std::stoi returns 7542 (because trailing '-' is not "part of integer").