在菜单前键入字符串后,C 如何从菜单中选择选项

C++ How to select option from the menu after typing a string before the menu?

本文关键字:菜单 选择 选项 字符串      更新时间:2023-10-16

我是C 的新手,我正在开发一个程序,其中学生在主题代码中键,然后有一个菜单,可以选择。

问题是,在输入和输入主题代码后,菜单及其选项将出现,但您退出系统而不是选择继续的选项。

这是我试图让它们工作的部分的代码

    void ProcessStudent(char option, char subjCode)
    {
        fstream binFile;
const char *fileName;
cout << "Welcome to Priya's UOW Student File Processingn" << endl;
cout << "Enter the module: ";
cin >> subjCode;
cout << "n1. Creation of binary filen";
cout << "2. Append a recordn";
cout << "3. Update a recordn";
cout << "4. Delete a recordn";
cout << "5. Produce final file (text file)n";
cout << "9. Quitn";
cout << "Your option: ";
cin >> option;
cout << "n" <<setw(60)<<setfill('-')<<'-'<<endl;
switch(option)
{
    case '1':
        CreateBinary(binFile,subjCode,fileName);
    break;
    case '2':
        AppendRec(binFile,option,fileName);
    break;
    case '3':
        UpdateRec(binFile,option,fileName);
    break;
    case '4':
        DeleteRec(binFile,option,fileName);
    break;
    case '5':
        FinalFile(binFile,option,fileName);
    break;
    case '9':
        MainMenu(option);
}
    }
    void CreateBinary(fstream& binFile, char subjCode, const char *fileName)
    {
    //    Student s;
srand(time(NULL));
        binFile.open(fileName, ios::out | ios::binary);
    //    binFile >> s.id;
    //    binFile.getline(s.name,MAX);
if(!binFile)
{
    cout << fileName << " opened for creation failed" << endl;
    exit(-1);
}
cout << "Begin creation of " << fileName << endl;
fstream txtFile;
txtFile.open(fileName, ios::in);
if(!txtFile)
{
    cout << fileName << " opened for reading failed" << endl;
    exit(-1);
}
cout << "Text file " << fileName << "opened for reading" << endl;

binFile.close();
txtFile.close();
cout << "Binary file " << fileName << " created" << endl;
cout << "Text file " << fileName << " closed for reading" << endl;
}

我要问的是,输入主题代码或任何其他字符串后,如何选择一个选项?我错过了代码中的任何东西吗?

希望你们明白我在问什么,如果不是让我知道。

提供的任何帮助都将不胜感激。非常感谢:)。

您需要冲洗cout流:

 cout << "Enter the module: " << flush;

及以后

 cout << "Your option: "  << flush;

终于用cout << endl

替换新线的输出

您应该使用所有警告和调试信息(例如g++ -Wall -g)进行编译,并学习如何使用debugger gdb)。也许有些功能,例如UpdateRec正在崩溃...