I have a MyFile.txt file, which contains numbers like 1 2 3 4 6. I need to swap the maximum and minimum values using Fstream. This is my function.
void file26 () {
Stack & LT; int & gt; Numbers;
FSTREAM FS;
FS.Open ("MyFile.txt", Fstream :: In | Fstream :: Out);
if (! fs.is_open ()) {
COUT & LT; & LT; "CAN't Open File MyFile.txt" & lt; & lt; Endl;
} else {
int min;
INT MAX;
int i_min = 0;
int i_max = 0;
int i = 0;
While (! fs.eof ()) {
String S;
FS & GT; & GT; s;
int x = stoi (s);
numbers.push (x);
if (i == 0) {
min = x;
max = x;
} else {
If (X & LT; MIN) {
SWAP (X, MIN);
i_min = i;
}
If (X & GT; MAX) {
SWAP (X, MAX);
i_max = i;
}
}
I ++;
}
i = numbers.size ();
While (! numbers.empty ()) {
int x = numbers.top ();
I--;
numbers.pop ();
if (i == i_min) {
X = MAX;
}
if (i == i_max) {
x = min;
}
COUT & LT; & LT; x & lt; & lt; "," & lt; & lt; Endl;
FS & LT; & LT; x & lt; & lt; "";
}
}
FS.Close ();
}
Answer 1, Authority 100%
Because You have already reached the end of the file, then an error of reading occurred at the end, as well as the pointer in the file is at the end of the file.
To get rid of the error mark. Use the Clear
And to return the pointer to the beginning of the file function seekp
Here is an example code:
fs.clear ();
FS.Seekp (0, iOS :: Beg);
While (! numbers.empty ()) {
....
}
Also, not my case, of course, but notice that the number will be recorded in the reverse order if you do not need it, you can use the vector & lt; int & gt; Numbers;