我正在尝试根据用户选择的 2 个文件对文件进行排序。我正在使用一个字符串变量并将其传递给,instream()
但它不断进入if
表明文件已损坏或不存在的语句。我知道它存在,因为当我硬编码文件名时,它工作得非常好!我确定它很简单,但我就是想不通。我对 c++ 很陌生,所以请仔细回答你的问题,以便我理解和学习。提前致谢!
#include <iterator>
#include <algorithm>
#include <vector>
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
std::string file = "";
std::ofstream out("outputfile.txt");
std::vector<int> numbers;
std::string sortType = "";
void sort(std::vector<int>);
void MergeSort(vector<int> &numbers);
int main()
{
std::cout << "Which type of sort would you like to perform(sort or mergesort)?\n";
std::cin >> sortType;
std::cout << "Which file would you like to sort?\n";
std::cin >> file;
std::ifstream in(file);
//Check if file exists
if(!in)
{
std::cout << std::endl << "The File is corrupt or does not exist! ";
return 1;
}
// Read all the ints from in:
std::copy(std::istream_iterator<int>(in), std::istream_iterator<int>(),
std::back_inserter(numbers));
//check if the file has values
if(numbers.empty())
{
std::cout << std::endl << "The file provided is empty!";
return 1;
} else
{
if(sortType == "sort")
{
sort(numbers);
}else
{
MergeSort(numbers);
}
// Print the vector with tab separators:
std::copy(numbers.begin(), numbers.end(),
std::ostream_iterator<int>(std::cout, "\t"));
std::cout << std::endl;
// Write the vector to a text file
std::copy(numbers.begin(), numbers.end(),
std::ostream_iterator<int>(out, "\t"));
std::cout << std::endl;
}
return 0;
}
void sort(std::vector<int>)
{
// Sort the vector:
std::sort(numbers.begin(), numbers.end());
std::unique(numbers.begin(), numbers.end());
return;
}
vector<int> Merge(vector<int> &left, vector<int> &right)
{
std::vector<int> result;
while (left.size() > 0 && right.size() > 0)
{
if (left[0] <= right[0])
{
result.push_back(left[0]);
left.erase(left.begin());
} else
{
result.push_back(right[0]);
right.erase(right.begin());
}
}
if (left.size() > 0)
{
result.insert(result.end(), left.begin(), left.end());
} else
{
result.insert(result.end(), right.begin(), right.end());
}
return result;
}
void MergeSort(vector<int> &numbers)
{
if (numbers.size() <= 1)
{
return;
}
// split vector into two peices
vector<int> left, right;
unsigned int Middle = numbers.size() / 2;
for (unsigned int i = 0; i < Middle; i++)
{
left.push_back(numbers[i]);
}
for (unsigned int i = Middle; i < numbers.size(); i++) {
right.push_back(numbers[i]);
}
MergeSort(left);
MergeSort(right);
numbers = Merge(left, right);
return;
}