您的位置:首页 > 编程语言 > C语言/C++

C++_文本文件读写常用代码

2014-08-25 14:04 190 查看

数据测试:有一个文件file.txt,内容入下:

[html]
view plaincopyprint?

This life will always love you.  
Let me always love you!   
If  you have locked in my memory, and that the key to keeping your life on it for me.   

This life will always love you.
Let me always love you!
If  you have locked in my memory, and that the key to keeping your life on it for me.

说明:省略了一些判断,如文件打开失败

1、逐词读入,放到字符串中,逐词处理

[cpp]
view plaincopyprint?

#include <iostream>  
#include <fstream>  
#include <string>  
using namespace std;  
void main()  
{  
    ifstream file("file.txt");  
    string word;  
    while (file>>word) // >>:读取成功,返回true,读取失败返回false  
    {  
        cout<<word<<endl;  
    }  
    system("pause");  
}  

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void main()
{
ifstream file("file.txt");
string word;
while (file>>word) // >>:读取成功,返回true,读取失败返回false
{
cout<<word<<endl;
}
system("pause");
}

运行结果:见一个单词换一行。

This

life

......

for

 me.

2、逐行输入,并放到字符数组中,逐行处理

[cpp]
view plaincopyprint?

#include <iostream>  
#include <fstream>  
using namespace std;  
void main()  
{  
    const int len=100;  
    char str[len];  
    ifstream file("file.txt");  
    while (file.getline(str,len))//len表示这次输入字符串的最大值,getline读取成功,返回true,读取失败返回false  
    {  
        cout<<str<<endl;  
    }  
    system("pause");  
}  

#include <iostream>
#include <fstream>
using namespace std;
void main()
{
const int len=100;
char str[len];
ifstream file("file.txt");
while (file.getline(str,len))//len表示这次输入字符串的最大值,getline读取成功,返回true,读取失败返回false
{
cout<<str<<endl;
}
system("pause");
}

运行结果:见一句换一行

This life will always love you.---第一次循环

Let me always love you!  ---第二次循环

If  you have locked in my memory, and that the key to keeping your life on it for me. ---第三次循环

注意:

    1)这个getline函数是 ifstream流 的成员函数

    2)如果一行中的数据长度超过len,就会读取失败,返回false

    3)第一个参数是 指针类型*,不能使用string类型

3、 逐行输入,存放字符串中,逐行处理

[cpp]
view plaincopyprint?

#include <iostream>  
#include <fstream>  
#include <string>  
using namespace std;  
void main()  
{  
    string str;  
    ifstream file("file.txt");  
    while(getline(file,str)) //getline:读取成功,返回true,读取失败返回false  
    {  
        cout<<str<<endl;  
    }  
    system("pause");  
}  

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void main()
{
string str;
ifstream file("file.txt");
while(getline(file,str)) //ge
4000
tline:读取成功,返回true,读取失败返回false
{
cout<<str<<endl;
}
system("pause");
}

注意:这个getline函数是 string 头文件中提供的一个函数,与上一个例子不同,使用要加头文件#include <string>

运行结果:见一句换一行

This life will always love you.---第一次循环

Let me always love you!  ---第二次循环

If  you have locked in my memory, and that the key to keeping your life on it for me. ---第三次循环

注意:>>从文件读入内存时,见到空格、Tab、回车 会停止接受

           file.getline():一行为单位,见到回车停止,但是见空格、Tab不停止
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: