在我的switch语句完全执行之前,我的while循环进入第二次迭代,我用c ++编码

My while loop goes into it's second iteration before my switch statement executes completely, I'm coding in c++

本文关键字:我的 第二次 迭代 我用 编码 循环 while 语句 执行 switch      更新时间:2023-10-16
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
void ReadFile()
{
    string fileName;
    ifstream inFile;
    cout << "Please enter the password for the external file: ";
    getline(cin, fileName);
    inFile.open(fileName);
}//End of ReadFile() function

int main()
{
    vector<string> studentName, studentNumber, studentClass;
    char option;
    while (option != 'g' && option != 'G')
    {
        cout << "ttt" << "Student List Menunn";
        cout << "A.  Reading the Student List from a filen";
        cout << "B.  Adding Student's Informations into the Student Listn";
        cout << "C.  Displaying the content of the Student Listn";
        cout << "D.  Sorting and Displaying the content of the Student Listn";
        cout << "E.  Writing the Student List to a filen";
        cout << "F.  Searching for a Student's Information from the Student Listn";
        cout << "G.  Ending the programnn";
        cout << "Please enter an option:     ";
        cin >> option;
        cout << endl;
        switch (option)
        {
            case 'A':
            case 'a':
                ReadFile();
                break;
            case 'B':
            case 'b':
                break;
            case 'C':
            case 'c':
                break;
            case 'D':
            case 'd':
                break;
            case 'E':
            case 'e':
                break;
            case 'F':
            case 'f':
                break;
            case 'G':
            case 'g':
                cout << "Thank you for using the program!";
                break;
            default: cout << "Invalid option choicenn";
        }
    }
    return 0;
}//End of main function

当我选择选项"A"时,switch 语句调用 ReadFile(( 函数,但是当它要求输入"密码"(文件名(时,会读取"学生列表菜单",我认为这意味着 do-while 循环在执行 ReadFile 函数时继续运行,因此它会读取输入直到换行符。我该怎么做才能让它先运行选项,然后继续执行 do-while 循环?

当您键入时

a

,然后按 Enter 键,在输入流中输入两个字符:a'n'

当您使用

cin >> option;

在此类输入流上,首先读取'a'。换行符仍在输入流中。

然后你调用ReadFile(),它调用getline(cin, fileName)。该调用将获得一个空字符串,因为换行符仍然存在于输入流中 - 它不会等待您输入文件名。之后,输入流中没有任何内容。此外,ReadFile()返回。这就是您看到学生菜单的原因。

该问题的解决方法是在读取option后忽略该行的其余部分。

cin >> option;
cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');

替换getline(cin, fileName);

cin>> fileName;

代码中的错误是由于行

getline(cin, fileName);

您必须使用

std::cin.getline(fileName,name length);