文件能够打开,但不返回任何内容

File is able to open but not returning anything?

本文关键字:返回 任何内 文件      更新时间:2023-10-16

我在尝试从.txt文件中获取行时遇到问题。我在另一段代码和文档中使用了类似的算法,似乎没有问题(= 打印了所有行)。但是,当我尝试使用 getline 做同样的事情时(像往常一样),我得到我的字符串行 = "。我的行不是空的,我有一个预测试来检查文件是否打开,它确实打开了。下面是我的程序中的一个函数。谁能提供一些帮助?谢谢!

我正在尝试运行案例"A"

  void Database::LoginMenu(string code)
  {
    cout << endl;
    cout << "Thank You for Login In, Would You Like To..." << endl;
    cout << "====================================================" << endl;
    cout << "A. View your registration information" << endl;
    cout << "B. Search for others" << endl;
    cout << "C. Search for Upcoming" << endl;
    cout << "D. Enter the Database" << endl;
    char choice, YN;
    cout << endl;
    cout << "Please choose an option: ";
    cin >> choice;
    switch(choice)
    {
    case 'A':
        {
            ifstream myfile("RegistrationInfo.txt");
            string line;
            if(myfile.is_open())
            {   
                while(!myfile.eof())
                {
                    getline(cin, line);
                    if(line[5] == ':')
                    {
                        line = line.substr(7, line.size());
                    }
                    if(line == code)
                    {
                        while(!line.empty())
                        {
                            cout << line << endl;
                        }
                    }
                }
            }   
            cout << "Would you like to return to the menu? (Y/N)";
            cin >> YN;      
            if(YN == 'Y')
            {
                LoginMenu(code);
            }
            myfile.close();
        }
        break;
    case 'B':
        {
            ifstream filein("RegistrationInfo.txt");
            string temp, YN, enteredInfo;
            int n = 0;
            cout << "Who do you wish to search for? :";
            cin >> enteredInfo;
            while(!filein.eof())
            {
                getline(cin, temp);
            }
        }
        break;
    case 'C': upcomingComps();
        break;
    case 'D': DatabaseMenu();
        break;
    }
  }

以下是我的txt文件中的几行。

  • 编号: abd50896
  • 姓名:汤姆·马伦·妮可·拉伯格
  • Compt: Rutgers DanceSport 2012
  • 级别:新人
  • 舞蹈:探戈华尔兹 快步伦巴 查查 吉夫

建议调用使用 myfile 作为第一个参数,而不是 cin -- getline(myfile, line) -- 因为 cin 表示 stdin,这不是您打开的文件。

最明显的是你打开了文件,但你正在从cin中读取。尝试将 cin 更改为 myfile。