美文网首页
C/C++读取固定格式文件(每一行以空格分开)

C/C++读取固定格式文件(每一行以空格分开)

作者: lxr_ | 来源:发表于2021-10-15 23:04 被阅读0次

例如文件如下

读取的文件
#include <iostream>

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

using namespace std;

int main(int argc, char** argv)
{
    vector<vector<int>> V;
    ifstream ifs("1.txt");//文件流对象
    if (!ifs)
    {
        cout << "文件打开失败" << endl;
    }
    string line; //读取一行
    while (getline(ifs, line))  //getline需要加上string头文件
    {
        stringstream ss(line);  //需要加上sstream头文件
        string s;
        vector<int> v;

        while (ss >> s)         //以空格为分隔符
        {
            v.push_back(atoi(s.c_str()));//先将读取的字符串转为c风格字符串,再转为int类型
        }
        V.push_back(v);//存入V中;
    }
    for (auto & v : V)  //打印读取结果
    {
        for (auto & i : v)
        {
            cout << i << " ";
        }
        cout << endl;
    }
    system("pause");
    return 0;
}

直接以数据对应的格式(int)读取(不需要以字符串读取在转为int)

int main(int argc, char** argv)
{
    vector<vector<int>> V;

    ifstream ifs("1.txt");

    if (!ifs)
    {
        cout << "文件打开失败!\n" << endl;
    }

    while (!ifs.eof())
    {
        int x, y, z;
        ifs >> x >> y >> z;       //读取每一行的三个数据
        vector<int> v;            //存放每一行数据
        v.push_back(x);
        v.push_back(y);
        v.push_back(z);

        V.push_back(v);           //将每一行组成的vector存入vector
    }

    for (auto& v: V)
    {
        for (auto&i : v)
        {
            cout << i << " ";
        }
        cout << endl;
    }

    system("pause");
    return 0;
}

C语言读取

int main(int argc, char** argv)
{
    FILE* fp;
    if ((fp = fopen("1.txt", "r"))==NULL)   //以读方式打开文件
    {
        printf("文件打开失败\n");
    }

    int a[1000][3];                        //二维数组记录读取结果,每一行有三个数据,最多读取1000行
    int row = 0;                           //记录读取多少行
    while (!feof(fp))                      //是否读取到文件末尾
    {
        int x, y, z;                       

        fscanf(fp, "%d%d%d", &x, &y, &z);  //格式化读取,读取的每一个数据直接存入对应的变量中

        a[row][0] = x;                     //更新读取的值
        a[row][1] = y;
        a[row][2] = z;
        row++;
    }

    for (int i = 0; i < row; i++)         //打印读取到的所有值
    {
        for (int j = 0; j < 3; j++)
        {
            printf("%d ", a[i][j]);
        }
        printf("\n");
    }
    
    system("pause");
    return 0;
}

读取结果如下

读取结果

相关文章

网友评论

      本文标题:C/C++读取固定格式文件(每一行以空格分开)

      本文链接:https://www.haomeiwen.com/subject/pqrvoltx.html