所以我正在运行一个让用户输入命令的程序。我有一个文本文件,其中包含可接受的命令字列表。我首先打开文件以确保用户输入确实是有效命令,但在该步骤之后我关闭文件。之后,我使用一些if / else语句来运行与该命令对应的函数。一个命令是列出所有有效命令,这需要我再次打开文件并简单地输出内容。但是,在此步骤中,程序不会输出任何内容。这是代码:
#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;
}
控制台看起来像这样:
||欢迎来到主菜单||
请输入命令。对于命令列表,键入&#34; comlist&#34; &GT;
此时我输入&#34; comlist&#34; 所需的结果是command.txt文件输出其内容。它应该是这样的:
comlist 命令2 指令代码 command4 command5
相反,屏幕保持空白,程序照常退出。 任何帮助将不胜感激。感谢。