如何在C ++中从文本文件读取矩阵 [英] How to read matrix from text file in C++

查看:118
本文介绍了如何在C ++中从文本文件读取矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

亲爱的所有人,
我有一些写在文本文件中的矩阵,我想将这些矩阵存储在2d整数数组中.我尝试使用getline读取它,但它会读取整行.我如何从文本文件中的特定位置读取.也是未知的.

我的文本文件就像

矩阵A是

2 4 8 10 2
1 2 5 7 11

矩阵B是
1 2 3
11 25 27

如果有人可以帮助我,那就太好了.

问候,
Ishtiaq

Dear All,
I have some matrix written in text file and I want to store these matrices in 2 d integer array.I have tried to read it using getline but it reads the whole line.How can I read from specific location in text file.Size of matrices is also unknown.

My text file is like

Matrix A is

2 4 8 10 2
1 2 5 7 11

Matrix B is
1 2 3
11 25 27

It would be really nice,if anyone body can help me.

Regards,
Ishtiaq

推荐答案

正如getline()的名称所暗示的,它用于一次读取整行...如果您想在以下位置读取整数一次...尝试一下:

As the name of getline() implies, it''s used for reading entire lines at a time... if you want to read an integer at a time... try this:

ifstream file;
file.open( "C:\\TestFile.txt");
int test[5] = {0};

for( int i=0; i<5; i++)
    file >> test[i];

file.close();


现在,对于此代码,我仅将5个数字读入一个平面1D数组中,但这应该使您对需要执行的操作有正确的认识.如果需要动态的数组,则必须动态分配数组:


Now for this code I just read in 5 numbers into a flat 1D array, but that should give you the right idea of what you need to do. If you need it to be dynamic, you''ll have to allocate the array dynamically:

int *test; //declare as pointer
test = new int[size]; //Allocate after you figure out the size

//After you''re done with it, deallocate
delete [] test;


这篇关于如何在C ++中从文本文件读取矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆