C++整行读取.txt文件

来源:互联网 发布:经期自慰 知乎 编辑:程序博客网 时间:2024/06/10 01:01

读取文件 lhc.txt,  内容如下:

zhongguo  1 2 3 4  chinese


#include<iostream>

#include<sstream>
#include<string>
#include<fstream>

int main()
{
        std::string filename = "lhc.txt";
        std::ifstream infile( filename.c_str() );
        std::string str1, str2 ;
        int a[4];

        std::string lineStr;
        std::stringstream ss;
        while ( std::getline(infile,lineStr) )
        {
            ss << lineStr;
            ss >> str1;
            for(int i=0; i<4; i++ )
                 ss >> a[i];

            ss >> str2;
        }
        std::cout << " str1 is " << str1 << " str2 is " << str2 << std::endl;

        for (int i=0; i<4; i++)
           std::cout << " the " << i << " num is: " << a[i] << std::endl;
        return 1;

}

////注意的是:  ss.clear() ;   //如果你想通过使用同一stringstream对象实现多种类型的转换,请注意在每一次转换之后都必须调用clear()成员函数。 

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

将数据写入到.txt文件

#include<stdio.h>   // this is C?

int main(){

        std::cout << "hello, world" << std::endl ;
        FILE *f_buffer ;
        f_buffer = fopen("zz_lhc.txt", "w") ; // this will create the file, if it does not exit.
        fprintf( f_buffer, "%s  ", "hello" ) ;
        double a = 2.3 ;
        fprintf( f_buffer, "%f\n", a ) ;  // \n  will change to another line.
        fprintf( f_buffer, "%f\n", a ) ;
        fclose( f_buffer ) ;

        return 1 ;
}

0 0
原创粉丝点击