代码将只接受一个用户输入文件,而不是其他的

Code will only accept one user input file instead of the other ones

本文关键字:文件 输入 其他 用户 一个 代码      更新时间:2023-10-16

我使用Visual studio在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 filen";
}
    for (int j = 0; j < 10; j++)
    {
        cout << "Which search? Pleast enter bst or redblackn";
        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 treen";
                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 treen";
                getline(cin, input);
            }
            if (input == "redblack")
            {
                cout << "nSearch for what word in the treen";
                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 treen";
                getline(cin, input);
            }
        myFile.close();
    return 0;
}
}
任何帮助解决我的问题,我都非常感激。就像我被困在一个无止境的for循环中。这个问题我已经找了几个小时了,但还是找不到解决办法。

可能,如果文件打开失败,!myFile.eof()永远不会为false,因为myFile.getline()的行为不像预期的那样(无限循环)。

如果打开失败,应该在错误消息后返回。

另外,你应该只做while(myFile.getline()),而不是检查eof。

试着找到Visual Studio存放可执行文件的位置,看看其他文本文件是否在那里。

你的print语句也应该是count <<"文本"& lt; & lt;endl;如果以"n"结尾,可能实际上并没有刷新打印缓冲区,这可能会导致丢失错误输出。