C++ File input works once, but not twice for the same file

97 Views Asked by At

So I am running a program that has the users input a command. I have a text file with a list of acceptable command words. I open the file first to make sure that what the user input is indeed a valid command, but after that step I close the file. After that, I use some if/else statements to run a function corresponding to the command. One command is to list all of the valid commands, which requires me to open the file again and simply output the contents. At this step, however, the program simply outputs nothing. Here is the code:

#include<iostream>
#include<string>
#include<fstream>

using namespace std;

void mainMenu();
void comJunc(string comString);
void comList();
bool isCommand(string comString);

int main()
{
    mainMenu();

    return 0;
}
void mainMenu()//This function inputs a command
{
    string comString;
    bool isCom = false;

    cout << endl;
    cout << "||Welcome to the main menu||\n\nPlease enter a command. For a list of commands type \"comlist\"\n";

    do
    {
        cout << ">";
        cin >> comString;//Input command "comlist"
        isCom = isCommand(comString);//Checks if command is valid
        if(isCom == false)
            cout << endl << "**Error** Command \"" << comString << "\" was not found. Type \"comlist\" for help\n";
    }while(isCom == false);

    comJunc(comString);

    return;
}
bool isCommand(string comString)
{
    bool sFlag = false;
    string inString;

    ifstream comFile;
    if(comFile.is_open() == false)
    {
        comFile.open("commands.txt");
    }

    while(getline(comFile, inString))
    {
        if(comString == inString)
            sFlag = true;
    }

    comFile.close();
    return sFlag;
}
void comJunc(string comString)//Executes function based on command
{
    //comlist, continue, start, customize, exit
    if(comString == "comlist")
    {
      comList();//Calles comList function
  }
    else if(comString == "exit")
    {
        //does nothing (exits)
    }
    else
        cout << "Error in comJunc";

    return;
}
void comList()
{
    string inString;
    ifstream comFile;

    if(comFile.is_open() == false)
    {
        comFile.open("command.txt");
    }

    while(getline(comFile, inString))//This loop is not executed
    {
        cout << "Random text";//Text is not displayed
        cout << endl << inString;
    }
    cout << endl;
    comFile.close();

    return;
}

The console looks like this:


||Welcome to the main menu||

Please enter a command. For a list of commands type "comlist" >


At which point I type "comlist" The desired result is for the command.txt file to output its contents. It should look like this:


comlist command2 command3 command4 command5


Instead, the screen is left blank and the program exits as usual. Any help would be greatly appreciated. Thanks.

0

There are 0 best solutions below