我正在使用 Visual Studios 在 C++ 中编码,我的代码将只接受名为“perm15K.txt”的文件。如果我尝试输入“perm30K.txt”或“sorted15K.txt”,我的代码将不会从中读取。它不会输出文件错误,但不会让我输入要执行的搜索。
#include "stdafx.h"
#include "binarysearchtree.h"
#include "redblacktree.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <ctime>
#include <chrono>
using namespace std;
int main()
{
struct bstnodes *root = NULL;
std::ifstream in;
std::ofstream out;
std::stringstream buffer;
buffer << in.rdbuf();
std::string test = buffer.str();
std::cout << test << std::endl << std::endl;
ifstream myFile;
string input;
string output;
cout << "Name of the input file? (ie. perm15K.txt)";
getline(cin, input);
myFile.open(input.c_str());
if (myFile.fail())
{
cout << "Error with file\n";
}
for (int j = 0; j < 10; j++)
{
cout << "Which search? Pleast enter bst or redblack\n";
binarysearchtree temp;
redblacktree temp1;
while (!myFile.eof())
{
while (getline(myFile, input)) {
myFile >> input;
string words = input;
temp.insert(words);
temp1.rbinsert(words);
}
}
getline(cin, input);
if (input == "bst")
{
cout << "\nSearch for what word in the tree\n";
getline(cin, input);
temp.insert(input);
clock_t start_s = clock();
std::cout << "Match Found: " << temp.search(input) << std::endl;
clock_t stop_s = clock();
double sum = ((double)(stop_s - start_s));
cout << endl << "Time: " << sum << " seconds" << endl;
cout << "\nSearch for what word in the tree\n";
getline(cin, input);
}
if (input == "redblack")
{
cout << "\nSearch for what word in the tree\n";
getline(cin, input);
temp1.rbinsert(input);
clock_t start_s = clock();
temp1.rbsearch(input);
std::cout << "Match Found: ";
clock_t stop_s = clock();
double sum = ((double)(stop_s - start_s));
cout << endl << "Time: " << sum << " seconds" << endl;
cout << "\nSearch for what word in the tree\n";
getline(cin, input);
}
myFile.close();
return 0;
}
}
非常感谢任何解决我的问题的帮助。就像我陷入了无休止的 for 循环。几个小时以来,我一直在努力寻找问题,但找不到解决方案。
最佳答案
可能,如果文件打开失败,!myFile.eof()
永远不会为假,因为 myFile.getline()
没有按预期运行(无限循环)。
打开失败请在错误提示后返回。
此外,您应该只执行 while(myFile.getline())
,而不是检查 eof。
关于c++ - 代码将只接受一个用户输入文件而不是其他文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39783233/