我正在尝试根据用户选择的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;
}
答案 0 :(得分:1)
您仍在检查名称""
提供的文件。放行
std::ifstream in(file);
它打开流到名称“”(此时file
的值)指定的文件的流。后来,你说
if (!in)
没有实际更新使用的文件。
试试这个:
std::ifstream in; //no file specified
//the following comes before if (!in)
in.open (file);
这将打开流到输入值file
。
更好的方法是只声明并打开文件代替第二行并丢失第一行:
std::ifstream in (file); //after they input the filename
如果您没有任何理由,使用全局变量通常是个坏主意。最好在函数中传递它们,或者在类中包含它们。
另外,我注意到您已声明using namespace std;
,但仍使用std::vector
等。我肯定会选择后者并删除前者。但是要注意将分辨率添加到那些遗漏它的东西中。
答案 1 :(得分:0)
在检查状态之前,您需要open()
该文件。