现在的位置: 首页 > 综合 > 正文

如何读取txt文件内容

2014年10月15日 ⁄ 综合 ⁄ 共 697字 ⁄ 字号 评论关闭

       读取txt文件内容有很多种方法,本文只简单介绍下使用ifstream和getline怎么样读取文件内容。

第一种方法:逐词读取, 词之间用空格区分


void ReadDataFromFileWBW()
{
    ifstream f(
"data.txt");  
    
string s;  
    
while( f>> s ) 
    
{    
        cout 
<< "Read from file: " << s << endl;  
    }

}

第二种方法: 逐行读取, 将行读入字符数组, 行之间用回车换行区分

void ReadDataFromFileLBLIntoCharArray()
{
    ifstream f(
"data.txt"); 
    
const int LINE_LENGTH = 100
    
char line[LINE_LENGTH];  
    
while( f.getline(line,LINE_LENGTH) )
    
{    
        cout 
<< "Read from file: " <<
line
<< endl;
    }

}

第三种方法:逐行读取, 将行读入字符串, 行之间用回车换行区分

void ReadDataFromFileLBLIntoString()
{
    ifstream f(
"data.txt");  
    
string s;  
    
while( getline(f,s) )
    
{    
        cout 
<< "Read from file: " << s << endl; 
    }

}

抱歉!评论已关闭.