【温故知新C/C++】01:C++ ofstream和ifstream||c_str||atoi

1. ofstream是从内存到硬盘,ifstream是从硬盘到内存,其实所谓的流缓冲就是内存空间;

  在C++中,有一个stream这个类,所有的I/O都以这个“流”类为基础的,包括我们要认识的文件I/Ostream这个类有两个重要的运算符:

  1、插入器(<<)

  向流输出数据。比如说系统有一个默认的标准输出流(cout),一般情况下就是指的显示器,所以,cout<<"Write Stdout"<<'/n';就表示把字符串"Write Stdout"和换行字符('/n')输出到标准输出流。

  2、析取器(>>)

  从流中输入数据。比如说系统有一个默认的标准输入流(cin),一般情况下就是指的键盘,所以,cin>>x;就表示从标准输入流中读取一个指定类型(即变量x的类型)的数据。

  在C++中,对文件的操作是通过stream的子类fstream(file stream)来实现的,所以,要用这种方式操作文件,就必须加入头文件fstream.h。下面就把此类的文件操作过程一一道来。

  一、打开文件

  在fstream类中,有一个成员函数open(),就是用来打开文件的,其原型是:

  void open(const char* filename,int mode,int access);参数:

  filename:  要打开的文件名

  mode:    要打开文件的方式

  access:   打开文件的属性

 

  打开文件的方式在类ios(是所有流式I/O类的基类)中定义,常用的值如下:

 

  ios::app:   以追加的方式打开文件

  ios::ate:   文件打开后定位到文件尾,ios:app就包含有此属性

  ios::binary: 以二进制方式打开文件,缺省的方式是文本方式。两种方式的区别见前文

  ios::in:   文件以输入方式打开(文件数据输入到内存)

  ios::out:   文件以输出方式打开(内存数据输出到文件)

  ios::nocreate:不建立文件,所以文件不存在时打开失败

  ios::noreplace:不覆盖文件,所以打开文件时如果文件存在失败

  ios::trunc:  如果文件存在,把文件长度设为0

 

  可以用“或”把以上属性连接起来,如ios::out|ios::binary

  打开文件的属性取值是:

  0:普通文件,打开访问

  1:只读文件

  2:隐含文件

  4:系统文件

  可以用“或”或者“+”把以上属性连接起来,如31|2就是以只读和隐含属性打开文件。

  例如:以二进制输入方式打开文件c:/config.sys

  fstream file1;

  file1.open("c://config.sys",ios::binary|ios::in,0);

 

  如果open函数只有文件名一个参数,则是以读/写普通文件打开,即:

  file1.open("c://config.sys"); <=> file1.open("c://config.sys",ios::in|ios::out,0);

另外,fstream还有和open()一样的构造函数,对于上例,在定义的时侯就可以打开文件了: fstream file1("c://config.sys");  

 

特别提出的是,fstream有两个子类:ifstream(input file stream)ofstream(outpu file stream)ifstream默认以输入方式打开文件,而ofstream默认以输出方式打开文件。

ifstream file2("c://pdos.def");//以输入方式打开文件 

ofstream file3("c://x.123");//以输出方式打开文件  所以,在实际应用中,根据需要的不同,选择不同的类来定义:如果想以输入方式打开,就用ifstream来定义;如果想以输出方式打开,就用ofstream来定义;如果想以输入/输出方式来打开,就用fstream来定义。

  

 

一般需添加头文件:

#include <iostream>
#include <fstream>
#include <string>

 

 

2.  string::c_str()函数

Syntax:
#include <string>

const char* c_str();

 

The function c_str() returns a const pointer to a regular C string, identical to the current string. The returned string is null-terminated.(返回的字符串以/0结尾—这是c语言中字符串的默认结尾符,所以该函数是将c++中的字符串string格式的变量转化为c中的字符串格式)

Note that since the returned pointer is of type const, the character data that c_str() returns cannot be modified. Furthermore, you do not need to call free() or delete on this pointer.

因为c_str函数的返回值是const char*的,不能直接赋值給char*。

c_str()返回一个客户程序可读不可改(因返回值是const char*)的指向字符数组的指针,不需要手动释放或删除这个指针。

+++++++++++++++++++++++++++++++++

Visual C++ Standard Library
basic_string::c_str

Converts the contents of a string as a C-style, null-terminated string.(返回以"/0"结尾的C-串,标准C中的字符串格式)


Return Value
A pointer to the C-style version of the invoking string. The pointer value is not valid after calling a non-const function, including the destructor, in the basic_string class on the object.

Remarks
Objects of type string belonging to the C++ template class basic_string<char> are not necessarily null terminated. The null character ' /0 ' is used as a special character in a C-string to mark the end of the string but has no special meaning in an object of type string and may be a part of the string just like any other character. There is an automatic conversion from const char* into strings, but the string class does not provide for automatic conversions from C-style strings to objects of type basic_string<char>.

The returned C-style string should not be modified, as this could invalidate the pointer to the string, or deleted, as the string has a limited lifetime and is owned by the class string.

++++++++++++++++++++++++++++++++

 

       string::c_str()函数返回一个const char*指针,作用就是把string类型的变量转化为C-字符串char* (以"/0"作为字符串的默认结尾)

      【如果要把一个char 转换成string, 可以使用 string s(char *);   】

       c_str函数的返回值是const char*的,不能直接赋值给char* ,所以就需要我们进行相应的操作转化(利用strcpy()函数)。

  c++语言提供了两种字符串实现,其中较原始的一种只是字符串的c语言实现。与C语言的其他部分一样,它在c++的所有实现中可用,我们将这种实现提供的字符串对象,归为c-串每个c-串char*类型的

  标准头文件<cstring>包含操作c-串的函数库。当调用库函数,客户程序提供的是string类型参数,而库函数内部实现用的是c-串,因此需要将string对象,转化为char*对象,而c_str()提供了这样一种方法,它返回一个客户程序可读不可改的指向字符数组的指针

+++++++++++++++++++++++++++++++++

语法:
const char *c_str();
c_str()函数返回一个指向正规C字符串的指针, 内容与本string串相同.
这是为了与c语言兼容,在c语言中没有string类型,故必须通过string类对象的成员函数c_str()把string 对象转换成c中的字符串样式。
注意:一定要使用strcpy()等函数来操作c_str()返回的指针
比如:最好不要这样:
char* c;
string s="1234";
c = s.c_str(); //c最后指向的内容是垃圾,因为s对象被析构,其内容被处理

应该这样用:
char c[20];
string s="1234";
strcpy(c,s.c_str());
这样才不会出错,c_str()返回的是一个临时指针,不能对其进行操作(只能对其拷贝)

再举个例子
c_str() 以 char* 形式传回 string 内含字符串
如果一个函数要求char*参数,可以使用c_str()方法:
string s = "Hello World!";
printf("%s", s.c_str()); //输出 "Hello World!"

c_str() 一个将string转换为 const* char的函数
++++++++++++++++++++++++++++++++++++

const * char c_str()
    一个将string转换为 const* char的函数。

    string的c_str()返回的指针是由string管理的。它的生命期是string对象的生命期。然后可以按C的方式使用这个指针,或把它的内容复制出来。

    例如:
        string s;
        cin>>s;
        const char *ch=s.c_str();

   这样就可以从标准输入里输入任意长的字符串,并按const *char来使用。

   如果要把一个char 转换成string, 可以使用 string s(char *);  

其他类型转换方式:

string 转 CString  
CString.format("%s", string.c_str());  

char 转 CString  
CString.format("%s", char*);  

----------------------------------------------------------------------------------------------------------

1,string -> CString  
CString.format("%s", string.c_str());  
用c_str()确实比data()要好.  
2,char -> string  
string s(char *);  
你的只能初始化,在不是初始化的地方最好还是用assign().  
3,CString -> string  
string s(CString.GetBuffer());  
GetBuffer()后一定要ReleaseBuffer(),否则就没有释放缓冲区所占的空间.  


《C++标准函数库》中说的  
有三个函数可以将字符串的内容转换为字符数组和C—string  
1.data(),返回没有”/0“的字符串数组  
2,c_str(),返回有”/0“的字符串数组  
3,copy()  


CString互转int  

将字符转换为整数,可以使用atoi、_atoi64或atol。  
而将数字转换为CString变量,可以使用CString的Format函数。如  
CString s;  
int i = 64;  
s.Format("%d", i)  
Format函数的功能很强,值得你研究一下。  

void CStrDlg::OnButton1()  
{  
// TODO: Add your control notification handler code here  
CString  
ss="1212.12";  
int temp=atoi(ss);  
CString aa;  
aa.Format("%d",temp);  
AfxMessageBox("var is " + aa);  
}  

sart.Format("%s",buf);  

CString互转char*  

///char * TO cstring  
CString strtest;  
char * charpoint;  
charpoint="give string a value";  
strtest=charpoint;  


///cstring TO char *  
charpoint=strtest.GetBuffer(strtest.GetLength());  

标准C里没有string,char *==char []==string  

可以用CString.Format("%s",char *)这个方法来将char *转成CString。要把CString转成char *,用操作符(LPCSTR)CString就可以了。  


CString转换 char[100]  

char a[100];  
CString str("aaaaaa");  
strncpy(a,(LPCTSTR)str,sizeof(a));  

 


3. CString类型的转换成int  
CString类型的转换成int  
将字符转换为整数,可以使用atoi、_atoi64或atol。  

//CString aaa = "16" ;
//int int_chage = atoi((lpcstr)aaa) ;  


而将数字转换为CString变量,可以使用CString的Format函数。如  
CString s;  
int i = 64;  
s.Format("%d", i)  
Format函数的功能很强,值得你研究一下。  
如果是使用char数组,也可以使用sprintf函数。

//CString ss="1212.12";  
//int temp=atoi(ss);  
//CString aa;  
//aa.Format("%d",temp);  


数字->字符串除了用CString::Format,还有FormatV、sprintf和不需要借助于Afx的itoa.

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
InputStream和OutputStream是Java IO库中的两个重要类。它们用于处理字节流的输入和输出操作。 InputStream是一个抽象类,它是所有字节输入流的父类。它提供了一系列方法来读取字节数据。例如,可以使用FileInputStream类来创建一个输入流对象,然后使用read()方法逐个字节地读取文件中的数据。\[1\]\[3\] OutputStream也是一个抽象类,它是所有字节输出流的父类。它提供了一系列方法来写入字节数据。例如,可以使用FileOutputStream类来创建一个输出流对象,然后使用write()方法将字节数据写入文件中。\[1\]\[2\] 这两个类可以用于文件的读取和写入操作。例如,可以使用FileInputStream读取一个文件的字节数据,然后使用FileOutputStream将读取到的字节数据写入另一个文件中,实现文件的复制功能。\[2\] 需要注意的是,在使用这两个类进行文件操作时,需要在操作完成后及时关闭流,以释放资源。可以使用try-finally或try-with-resources语句来确保流的关闭。\[1\]\[2\]\[3\] #### 引用[.reference_title] - *1* *2* [java基础io流——OutputStream和InputStream的故事(温故知新)](https://blog.csdn.net/weixin_36586120/article/details/80486112)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [InputStream和OutputStream](https://blog.csdn.net/sspudding/article/details/88673551)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值