Reputation: 1
I am coding in C++ using Visual Studios and my code will only accept a file called "perm15K.txt". If I try to enter "perm30K.txt" or "sorted15K.txt" my code will not read from it. It does not output an error with file, but it will not let me enter which search I would like to perform.
#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;
}
}
Any help figuring out my problem is greatly appreciated. It is like I am stuck in an endless for loop. I have been trying to find the problem for a couple hours now and can't find a solution.
Upvotes: 0
Views: 66
Reputation: 1342
Possibly, if the file opening fails !myFile.eof()
is never false as myFile.getline()
doesn't behave as expected (infinite loop).
You should return after the error message if the opening fails.
Also, you should just do while(myFile.getline())
, rather than checking for eof.
Upvotes: 1
Reputation: 16
Try to find where Visual Studio is putting your executable and see if the other text files are there.
Also your print statements should be cout << "text" << endl; If you end them with "\n" you might not actually be flushing the print buffer which could be causing you to lose error output.
Upvotes: 0