C++逐行读取文本文件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/mengxiangjia_linxi/article/details/78265678
/**
数据:逐行读取文本文件.txt

逐行读取文本文件实例:
10
0 1 1 1 1 1 0 0 0 0
0 0 0 0 0 1 0 1 0 0
0 0 0 1 0 1 0 0 0 0
0 1 0 1 0 1 0 1 1 0
0 1 0 1 0 1 0 1 0 0
0 1 1 1 0 1 0 1 0 1
0 1 0 0 0 1 0 1 0 1
0 1 0 1 1 1 0 1 0 0
1 0 0 0 0 0 0 1 0 0
0 0 0 0 1 1 1 1 0 0

*/

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

using namespace std;

int main(void)
{
    string str;    //存第一行字符串
    int size = 0;  //存第二行的数组大小
    int a[10][10]; //存第三行开始的数组

    //这里主要为getline读取第一行的字符串,因getline为istream类型
    ifstream outfile("逐行读取文本文件实例.txt", ios::out | ios::binary); //以输出 | 二进制方式打开.txt文本。
    getline(outfile, str); //读outfile中一行  //补充一个:size = stoi(str);string转int
    cout << str << endl;   //输出字符串
    outfile.close();       //读取后关闭

    FILE *f;
    f = fopen("逐行读取文本文件实例.txt", "r"); //以只读方式打开文本
    fscanf(f, "%s*[\n]", &str);   //将读取文件的指针跳到下行(第二行)行首
    //cout << str << endl;        /*这里输出str将错误*/
    fscanf(f, "%d*[^\n]", &size); //将读取文件的指针跳到下行(第三行)行首
    cout << size << endl;

    //读取数组
    for (int i = 0; i < size; i++)
    {
        for (int j = 0; j < size; j++)
        {
            fscanf(f, "%d", &a[i][j]);
        }
    }

    fclose(f);  //读取完毕关闭文件

    //打印数组
    for (int i = 0; i < size; i++)
    {
        for (int j = 0; j < size; j++)
            cout << a[i][j];
        cout << endl;
    }

    cin.get();
    //cin.get();
    return 0;
}

结果:
这里写图片描述

猜你喜欢

转载自blog.csdn.net/mengxiangjia_linxi/article/details/78265678