1. I have few data in "MyData.txt" :
9 7 4 4 6 5 9 1 3 4 7 6 5 4 1 4 8 6 4 8 5
I only can copy the data into the code like this :
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char **argv){
char ofilename[] = "Sort-MyData.txt";
ofstream fout;
fout.open(ofilename);
const int n = 21;
int x[n] = {9, 7, 4, 4, 6, 5, 9, 1, 3, 4, 7, 6, 5, 4, 1, 4, 8, 6, 4, 8, 5};
for(int i = 0; i < n; i++) {
cout << x[i] << " ";
}
cout << endl;
for(int i = 0; i < n-1; i++) {
for(int j = i+1; j < n; j++) {
if(x[i] > x[j]) {
int buf = x[j];
x[j] = x[i];
x[i] = buf;
}
}
}
for(int i = 0; i < n; i++) {
fout << x[i] << " ";
}
fout.close();
cout << endl;
system("pause");
}
And the result in "Sort-MyData.txt" :
1 1 3 4 4 4 4 4 4 5 5 5 6 6 6 7 7 8 8 9 9
So the code is true.
But if I "call" the input from the code :
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char **argv){
//Input file
char ifilename[] = "MyData.txt";
ifstream fin;
fin.open(ifilename);
//Output file
char ofilename[] = "Sort-MyData.txt";
ofstream fout;
fout.open(ofilename);
//Check whether the ifilename exists
if (!fin) {
cerr << "Error!" << ifilename;
cerr << "could not be opened" << endl;
exit (1);
}
//Reading input file, I'm confused here :(
int i;
const int n = 21;
int x[n];
while (!fin.eof()) {
fin >> x[n];
i++;
}
//Show the original data
for (int i = 0; i < n; i++){
cout << x[i] << " ";
}
//Sort the data
for(int i = 0; i < n-1; i++) {
for(int j = i+1; j < n; j++) {
if(x[i] > x[j]) {
int buf = x[j];
x[j] = x[i];
x[i] = buf;
}
}
}
//Save output
for(int i = 0; i < n; i++) {
fout << x[i] << " ";
}
fin.close();
fout.close();
system("pause");
}
It shows strange number in "Sort-MyData.txt" :
-1 0 0 0 0 2 28 530 1088 1096 2292980 2293004 2293068 2503056 4198400 4198400 4198400 4198400 1977537193 2000486448 2000494924
I think there's something wrong in code for reading input file.
What should I do?
2. Then how to make 3 equal classes for "Sort-MyData.txt"?
3. If I have so many data in "MyData.txt",
(let say that there are thousands lines of data and there are hundreds data in each line),
what should I do?
(Because I don't know exactly how many data in "MyData.txt" and it is impossible to count it)
Thank you. :)