Reputation: 45
I was bit curious if I was going about this the wrong way. I am trying to read numbers from two different lists, sort the numbers, and then output ALL the numbers to a3rd file. I understand getline is probably not the best option but I still would like to use it.
list1 = 1,4, 5, 18
list2 = 2, 3, 15, 16
output = 1, 2, 3, 4,5, 7, 15,16 - what i should get
what i actually get - 1, 3, 5, 16
Here's a portion of the code
void sorted(std::ifstream &ifs, std::ifstream &ifs1, std::ofstream &ofs){
//while ((!ifs.eof()) & (!ifs1.eof())){
//int number = 0;
//int number1 = 0;
std::string num1;
std::string num2;
//getline(ifs, num1);
//getline(ifs1, num2);
while(std::getline(ifs, num1) && std::getline(ifs1, num2)){
int number = 0;
int number1 = 0;
std::stringstream ss1;
std::stringstream ss2;
ss1 << num1;
ss2 << num2;
ss1 >> number;
ss2 >> number1;
//while(ss1 >> number && ss2 >> number1)
//{
if (number < number1){
ofs << number << std::endl;
ss1 >> number;
std::cout << "am i doing this right?";
}
else{
ofs << number1 << std::endl;
ss2 >> number1;
}
}
}
Upvotes: 0
Views: 70
Reputation: 375
You are discarding one number in each pair each iteration because your if (number < number1) ... else
block only ever writes one of the two numbers out.
Try...
if (number < number1){
ofs << number << std::endl;
ofs << number1 << std::endl;
...
}
else{
ofs << number1 << std::endl;
ofs << number << std::endl;
...
}
Upvotes: 0
Reputation: 15824
getline
is the best option, no doubt and it is always better than your commented line of code using eof
. As Joachim mentioned in comment, you can first read the numbers from file to a std::vector container and call std::sort algorithm on top of vector.
Upvotes: 1