C++编译代码出现 ‘ios‘ has not been declared 解决办法

C++编译代码出现 ‘ios’ has not been declared 解决办法

我一开始是为了测试黑马程序员的教程中关于文件操作中的“读文件”部分程序,发现这个问题。

测试代码如下:

#include <iostream>
//#include <iosfwd>
#include  <unistd.h>
#include  <string>
#include <fstream>
//#include <ofstream>
//#include <ifstream>

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;
}

有两种解决方法:

  1. 确保有输入输出流头文件以及std命名空间。

    #include <iostream>
    
    using namespace std;
    

    如果是还有文件读写操作,还需要包含文件流的头文件:

    #include <fstream>
    

    这样的话在ios:in的地方就不会报错说没有声明了。

  2. 或者不声明std命名空间,在ios部分直接前面添加域名std即可。

    std::ifstream ifs; 
    	ifs.open("test.txt",std::ios::in);
    

在这之前其实尝试了CSDN上很多的方法都没有很好很有效地解决,如果本方法仍然存在问题,欢迎大家指出;如果有用,非常荣幸能够帮助到您。

  • 9
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值