将两个尺寸未知的文本文件中的两个矩阵相乘
Multiplying two matrices from two text files with unknown dimensions
这是我在这里的第一篇文章。我已经研究这个c++问题有一段时间了,但一无所获。也许你们可以给我一些提示,让我开始。
我的程序必须读取两个.txt文件,每个文件包含一个矩阵。然后,它必须将它们相乘,并将其输出到另一个.txt文件中。不过,我在这里的困惑是如何设置.txt文件以及如何获取尺寸。下面是矩阵1.text.的一个例子
#ivalue #jvalue value
1 1 1.0
2 2 1
矩阵的尺寸为2x2。
1.0 0
0 1
在开始乘以这些矩阵之前,我需要从文本文件中获得I和j的值。我发现的唯一方法是
int main()
{
ifstream file("a.txt");
int numcol;
float col;
for(int x=0; x<3;x++)
{
file>>col;
cout<<col;
if(x==1) //grabs the number of columns
numcol=col;
}
cout<<numcol;
}
问题是我不知道如何到达第二行来读取行数。除此之外,我不认为这会给我其他矩阵文件的准确结果。
如果有什么不清楚的地方,请告诉我。
更新谢谢我得到了正确工作的线索。但现在我遇到了另一个问题。在矩阵B中,设置为:
#ivalue #jvalue Value
1 1 0.1
1 2 0.2
2 1 0.3
2 2 0.4
我需要让程序知道它需要下降4行,甚至更多(矩阵维度未知。我的矩阵B示例是2x2,但它可能是20x20)。我有一个while(!file.of())循环我的程序,让它循环到文件末尾。我知道我需要一个动态数组来相乘,但这里也需要一个吗?
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream file("a.txt"); //reads matrix A
while(!file.eof())
{
int temp;
int numcol;
string numrow;
float row;
float col;
for(int x=0; x<3;x++)
{
file>>col;
if(x==1)
{
numcol=col; //number of columns
}
}
string test;
getline(file, test); //next line to get rows
for(int x=0; x<3; x++)
{
file>>test;
if(x==1)
{
numrow=test; //sets number of rows
}
}
cout<<numrow;
cout<<numcol<<endl;
}
ifstream file1("b.txt"); //reads matrix 2
while(!file1.eof())
{
int temp1;
int numcol1;
string numrow1;
float row1;
float col1;
for(int x=0; x<2;x++)
{
file1>>col1;
if(x==1)
numcol1=col1; //sets number of columns
}
string test1;
getline(file1, test1); //In matrix B there are four rows.
getline(file1, test1); //These getlines go down a row.
getline(file1, test1); //Need help here.
for(int x=0; x<2; x++)
{
file1>>test1;
if(x==1)
numrow1=test1;
}
cout<<numrow1;
cout<<numcol1<<endl;
}
}
"问题是我不知道如何到达第二行读取行数。"
使用std::getline
到达下一行。
std::string first_line;
std::getline( file, first_line );
相关文章:
- 如何在C++中从两个单独的for循环中添加两个数组
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 当在同一名称空间中有两个具有相同签名的函数时,会发生什么
- 如何返回一个类的两个对象相加的结果
- 如何在C++中将一个无符号的 int 转换为两个无符号的短裤?
- 如何将两个不同矢量的同一位置的两个元素组合在一起
- 两个字符串在 c++ 中不相等
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 两个文件使用彼此的功能-如何解决
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 如何确保在使用基于布尔值的两个方法之一调用方法时避免分支预测错误
- 停止cmake target_link_libraries将插件中静态库的两个对象文件链接到静态库本身
- 将fold表达式与std::一起用于两个元组
- 如何在C++中比较两个char数组
- 给定两个偶数,求出它们之间所有偶数的平方和
- 比较两个大小不等的映射c++
- C++需要帮助从用户那里获得一个整数,并确保它在另外两个整数之间
- 比较两个整数在C++中与未知 int 类型的相等性
- 将两个尺寸未知的文本文件中的两个矩阵相乘
- 如果两个维度在编译时都是未知的,如何传递二维数组