C++的如何在打开一个文本后,一行一行的读取内容?

C++的如何在打开一个文本后,一行一行的读取内容?给出详细的做法

    假如定义一个文本,格式如下: 

    1 2 3
    2 3 4
    3 4 5
    5 6 7
    7 8 9

    文件名为test.txt(包含5行)

    C++代码如下:

    #include <iostream>

    #include <sstream>

    #include <fstream>

    #include <string>

    int main(int args, char **argv)

    {

    std::ifstream fin("split.txt", std::ios::in);

    char line[1024]={0};

    std::string x = "";

    std::string y = "";

    std::string z = "";

    while(fin.getline(line, sizeof(line)))

    {

    std::stringstream word(line);

    解读代码:

    word >> x;

    word >> y;

    word >> z;

    std::cout << "x: " << x << std::endl;

    std::cout << "y: " << y << std::endl;

    std::cout << "z: " << z << std::endl;

    }

    fin.clear();

    fin.close();

    return 0;

    }

    下面介绍代码:首先说明一下头文件,头文件中<iostream>, <string>的作用就不用说了,<fstream>是定义文件的需要的头文件,而<sstream>是字符串流stringstream所需要的头文件。

    第8行: std::ifstream fin("split.txt", std::ios::in); 定义读取的文本文件。

    第9行: char line[1024] = {0}; 用于定义读取一行的文本的变量。

    第10--12行,定义了 x y z 三个字符串变量,用于存放读取一行数据后,分别存放每行的三个数据。

    第13--22行,用一个循环读取每行数据,读取行的函数是getline()函数,然后利用stringstream将每行文本自动按照空格分列,并分别存放到对应的三个字符串变量中。

    23、24行代码,就是刷新缓存,并关闭文件。

温馨提示:答案为网友推荐,仅供参考
第1个回答  2012-04-09
怎么不喜欢给分呢?C里面有一个getline函数,是一次读取一行的
第2个回答  2012-04-11
#include <iostream>;
#include <string>;

char fileName[] = "C:\\test.txt";
ifstream in(fileName);
string line;
while(getline(line, in)) {
cout << line << endl;
}本回答被提问者采纳
第3个回答  2012-04-09
c++里面也有getline,查查书吧,有些问题多看书是王道
相似回答