想读取一txt文件 执行程序时 总显示不能读取文件 劳烦各位给纠正 纠正,该如何处理

想读取一txt文件 执行程序时 总显示不能读取文件 劳烦各位给纠正 纠正
C/C++ code
#include <iostream>
#include <fstream>

#include "parsemonitormessage.h"

using namespace std;

ParseMonitorMessage parseMonitorMessage;

int main()
{
  string msg;
  ifstream infile("monitorprotocol.txt");
  if(!infile.is_open())
  {
    cerr<<"Error! can not open file!"<<endl;
    exit(EXIT_FAILURE);
  }
 else
  {
     while(infile>>msg)
     {
       parseMonitorMessage.ParseMsg(msg);
     }
  }
  return 0;
}


------解决方案--------------------
看不出你的代码里那里显示了can not read file,是指can not open file吗?如果是这样的话,说明文件没有正确打开,检查一下monitorprotocol.txt这个文件和你的程序的可执行文件是否在同一个目录下,应该在同样的目录下或者至少得在你的project所在目录下(这个具体位置跟IDE环境有关)才能打开。
------解决方案--------------------
int main()
{
cout<<"hello,c++"<<endl;
return 0;
}
//有几次我的codeblocks自己坏掉了,hello,c++都无法打印。。。
//然后我就不知道了。。。
------解决方案--------------------
直接这样判断试试。。。
 if(infile)
------解决方案--------------------
C/C++ code
// basic_filebuf_is_open.cpp
// compile with: /EHsc
#include <fstream>
#include <iostream>

int main( ) 
{
   using namespace std;
   ifstream file;
   cout << boolalpha << file.rdbuf( )->is_open( ) << endl;

   file.open( "basic_filebuf_is_open.cpp" );
   cout << file.rdbuf( )->is_open( ) << endl;
}

------解决方案--------------------
探讨
引用:
你的文件放哪儿啦?infile.open("monitorprotocol.txt") 是从当前工作目录去找这个文件,默认的当前工作路径是工程所在目录。
我的文件和源码是放在一起的

------解决方案--------------------
楼主,你可以试下,随便一个文件名,把他的打开方式设置为不存在则创建一个新文件,试下。。。