我一开始是为了测试黑马程序员的教程中关于文件操作中的“读文件”部分程序,发现这个问题。
测试代码如下:
#include//#include #include #include #include //#include //#include using namespace std; // using iostream::ios; //using namespace std; void test01() { std::ifstream ifs; ifs.open("test.txt",std::ios::in); if (!ifs.is_open()) { std::cout << "文件打开失败" << std::endl; return; } //第一种方式 char buf[1024] = { 0 }; while (ifs >> buf) { std::cout << buf << std::endl; } //第二种 //char buf[1024] = { 0 }; //while (ifs.getline(buf,sizeof(buf))) //{ // cout << buf << endl; //} //第三种 //string buf; //while (getline(ifs, buf)) //{ // cout << buf << endl; //} // // char c; // while ((c = ifs.get()) != EOF) // { // std::cout << c; // } // ifs.close(); } int main() { test01(); pause(); return 0; }
有两种解决方法:
-
确保有输入输出流头文件以及std命名空间。
#include
using namespace std; 如果是还有文件读写操作,还需要包含文件流的头文件:
#include
这样的话在ios:in的地方就不会报错说没有声明了。
-
或者不声明std命名空间,在ios部分直接前面添加域名std即可。
std::ifstream ifs; ifs.open("test.txt",std::ios::in);
在这之前其实尝试了CSDN上很多的方法都没有很好很有效地解决,如果本方法仍然存在问题,欢迎大家指出;如果有用,非常荣幸能够帮助到您。
暑期编程PK赛 得CSDN机械键盘等精美礼品!


