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

时间:2012-05-02 05:38:01

标签: c++ text-files ifstream getline

我在尝试从.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文件中的几行。

  • CCode:abd50896
  • 姓名:TomMullen NicoleLaBerge
  • Compt:Rutgers DanceSport 2012
  • 等级:新人
  • 舞蹈:Tango Waltz Quickstep Rumba ChaCha Jive

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

最明显的是你打开文件但是你正在阅读cin。尝试将cin更改为myfile。

相关问题