c++文件操作std::ifstream std::string::find() 和 std::string::npos
2016-04-20 14:17
811 查看
c++文件操作std::ifstream
标签: c++2015-02-04 20:51 1908人阅读 评论(0) 收藏 举报
分类:
编程语言 c++(24)
版权声明:本文为博主原创文章,未经博主允许不得转载。
C++对文件操作相关:
ifs.is_open() 判断文件是否打开
ifs.get() 获取文件的一个字符
ifs.good() 判断文件是否结束
std::ifstream::in 以只读的方式打开
[cpp] view
plain copy
#include <iostream>
#include <fstream> // std::ifstream
using namespace std;
int main(int argc, char *argv[])
{
std::ifstream ifs("a.cpp", std::ifstream::in);//only read
if(ifs.is_open())
{
std::cout<<"file is already open"<<endl;
}
char c = ifs.get();
while(ifs.good())
{
std::cout<<c;
c = ifs.get();
}
ifs.close();
return 0;
}
code from:http://www.cplusplus.com/reference/fstream/ifstream/ifstream/
std::string::find() 和 std::string::npos
(2008-04-20 10:20:54)转载▼
标签:
| 分类: MSN搬家 |
int idx = str.find("abc");
if (idx == string::npos)
...
上述代码中,idx的类型被定义为int,这是错误的,即使定义为 unsigned int 也是错的,它必须定义为 string::size_type。
npos 是这样定义的:
static const size_type npos = -1;
因为 string::size_type (由字符串配置器 allocator 定义) 描述的是 size,故需为无符号整数型别。因为缺省配置器以型别 size_t 作为 size_type,于是 -1 被转换为无符号整数型别,npos 也就成了该型别的最大无符号值。不过实际数值还是取决于型别 size_type 的实际定义。不幸的是这些最大值都不相同。事实上,(unsigned long)-1 和 (unsigned short)-1 不同(前提是两者型别大小不同)。因此,比较式 idx == string::npos
中,如果 idx 的值为-1,由于 idx 和字符串string::npos 型别不同,比较结果可能得到 false。
要想判断 find() 的结果是否为npos,最好的办法是直接比较:
if (str.find("abc") == string::npos) { ... }
(EOF)
相关文章推荐
- c++知识总结
- C++编程中的函数指针初步解析
- C语言02基础深入理解(二)
- C 数列计算问题
- C++中的c_str()函数用法
- Hypertable 简介 一个 C++ 的Bigtable开源实现
- C++ WINDOWS API 如何使用NMAKE和CL编译
- C++编写DLL的方法
- segmentation fault (core dumped) 调试
- C++ map关联容器删除元素
- C++单例
- 详解C语言结构体中的函数指针
- 学C++百度
- 详解C语言的结构体中成员变量偏移问题
- c++ 读入字符的函数简介
- 第4周 C语言及程序设计提高例程-9 函数的嵌套调用
- 强大的c/c++测试工具--lint简介
- 实例讲解C语言编程中的结构体对齐
- C语言的小算法技巧
- 解析C语言中结构体struct的对齐问题