【问题标题】:Why does my C++ cmd screen hang when I try to access a file to store data?当我尝试访问文件以存储数据时,为什么我的 C++ cmd 屏幕会挂起?
【发布时间】:2015-07-24 17:50:46
【问题描述】:

我已经尝试了几个小时来解决这个问题,但我真的不明白出了什么问题。当我尝试创建教师对象进入文件时,我的 Visual Studio 卡在 cmd 屏幕上,我可以选择任何按钮继续。

这是我的代码。请帮助我,我是 cpp 的新手:

    void populateActivityVector()
   {
    activity.clear();//for new data
    string temp = "";
    Activity tempActivity;
    ifstream inFile;
    try 
    {
        inFile.open("activity.txt", ios::in);
        while (!inFile.eof())
        {
            getline(inFile, temp);
            tempActivity.setID(temp);

            getline(inFile, temp);
            tempActivity.setName(temp);

            cout << temp << endl;
            activity.push_back(tempActivity);
        }
        inFile.close();
    }
    catch (std::ifstream::failure &readerr)
    {
        cout << "Reading Failed" << endl;
    }

    for (int i = 0; i < activity.size(); i++)
    {
        cout << activity[i].getID()<< endl;
    }
}

void main(){

    populateActivityVector();
    cout << "Succesfully complete!" << endl;
    cin.ignore();
    system("pause");
}

它没有显示文件中的数据请帮助我。

【问题讨论】:

  • 您没有检查流故障(仅 eof) - 您可以使用 while(stream) 而不是 while (!inFile.eof())
  • 我尝试检查文件是否正在被读取,但它甚至没有读取文件我不知道为什么......当我将下面的代码放在 while 循环中进行测试时......它显示了这个但是它永远不会结束 cout
  • 程序可能试图在不同的目录中查找文件...或者问题可能出在其他地方...由于您使用的是 Visual Studio,您是否尝试过调试?逐行检查变量下的值可能会有所帮助...
  • @Don“我的 Visual Studio 卡在 cmd 屏幕上,我可以选择任何按钮继续”.....你到底希望 system("pause"); 做什么?
  • 这不是@Jeff 我想说的是......屏幕挂起,无论你按什么键......它都不会关闭......就像你使用 ..system("pause" ) 它显示一个带有闪烁光标的黑屏

标签: c++ error-handling


【解决方案1】:

在你按下任何键之前“卡在cmd屏幕上”听起来像是

system("pause");

【讨论】:

  • 不。它只是挂起..我不知道为什么..我尝试了几台电脑,它给出了相同的结果
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-10-21
  • 2021-05-10
  • 2021-01-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多