I have a program which sorts numbers written for a text file.
For example input.txt contains 4 2 0 3 4 1 2 0 7.
The fist number is the number of the data points, and the following are the (x,y) coordinates.
Here's my code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main ()
{
string num;
int i,j,x,y,temp,temp1;
ifstream infile;
infile.open ("input.txt");
getline(infile,num); // Saves the line in STRING.
cout << num << endl;
cout << "No of points listed: " << num[0] << endl; // It will output 4
for(x=2,y=4;x<=num.length(),y<=num.length();x=x+4,y=y+4)
{
cout << "Points : [" << num[x] << "," << num[y]<< "]" << endl;
// It will output (2,0) (3,4) (1,2) (0,7)
};
cout << " Sorted " << endl;
for(i=num.length()-1;i>0;i--)
{
for(j=2;j<i;j+=4)
{
if (num[j]>num[j+4])
{
temp = num[j];
temp1= num[j+2];
num[j]=num[j+4];
num[j+2]=num[j+6];
num[j+4] = temp;
num[j+6] = temp1;
}
}
}
for(x=2,y=4;x<=num.length(),y<=num.length();x=x+4,y=y+4)
{
if(num[x]==num[x+4])
{
if(num[y]>num[y+4])
{
temp = num[y];
num[y]=num[y+4];
num[y+4]=temp;
}}
cout<<"Points: ["<< num[x]<<","<< num[y]<<"]";
// It will output sorted (0,7)(1,2)(2,0)(3,4)
cout<<endl;
}
system ("pause");
}
The only problem is when i use digits with tens or hundreds places.
For example the input.txt contains: 3 22 10 6 17 13 5
The correct output should be: (22,10)(6,17)(13,5) sorted (6,17)(13,5)(22,10)
However the output is: (2, )(0,6)(1, )(3,5) sorted (0,6)(1, )(2, )(3,5)
I think the cause of this is the program reads the space in the input file as an element of the string and a two digit number two elements which is why there are blank spaces and missing numbers.
Is there a better way to code my program so that the spaces will not count as elements and numbers with two or more digits will only count as one element in the string.
Thank you guys very much =))