【发布时间】:2014-12-15 13:45:26
【问题描述】:
以下代码在读取两个包含两个 5X5 数组的 .txt 文件时可以正常工作。
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <stdio.h>
#include <vector>
#include <sstream>
using namespace std;
int main()
{
string myFile, mysecondFile, mystring;
string DIR;
string extension;
int total = 0;
int number_of_lines = 0;
string line;
extension = ".txt";
DIR = "H:\\Year2\\EE273\\EE273\\Week6\\";
cout << "Enter the name of the file: \t";
cin >> myFile;
cout << "Enter the name of the second file: \t";
cin >> mysecondFile;
myFile = DIR + myFile + extension;
mysecondFile = DIR + mysecondFile + extension;
ifstream inFile;
ifstream inFile2;
int i=5;
int j=5;
int i2=5;
int j2=5;
int i3=5;
int j3=5;
int k;
int l;
int Array[5][5];
int Array2[5][5];
int Array3[5][5];
string attempt1,attempt2;
int row = 0;
int col = 0;
int row2 = 0;
int col2 = 0;//i = row
//y = column
inFile.open(myFile.c_str());
if (!inFile) {
cout <<"Error opening file"<<myFile<<endl;
return -1;
}
while (!inFile.eof())
{
getline(inFile, attempt1);
stringstream iss( attempt1 );
string result;
col = 0;
while (getline( iss, result, ','))
{
//cout << result << endl;
Array[row][col] = atoi(result.c_str());
//j = j + 1;
col = col + 1;
}
row = row + 1;
}
inFile.close();
inFile2.open(mysecondFile.c_str());
if (!inFile2) {
cout <<"Error opening file"<<mysecondFile<<endl;
return -1;
}
while (!inFile2.eof())
{
getline(inFile2, attempt2);
stringstream iss( attempt2 );
string result2;
col2 = 0;
while (getline( iss, result2, ','))
{
//cout << result2 << endl;
Array2[row2][col2] = atoi(result2.c_str());
col2 = col2 + 1;
}
row2 = row2 + 1;
}
inFile2.close();
/*for (int i=0;i<5;i++){
for (int j=0; j<5; j++){
cout<<Array[i][j]<<endl;}}
for (int i2=0;i2<5;i2++){
for (int j2=0; j2<5; j2++){
cout<<Array2[i2][j2]<<endl;
}}
我在这里执行两个矩阵之间的乘法并将结果值写入第三个矩阵。
int Total=0;
i=0;
j2=0;
j=0;
j3=0;
for (i3=0; i3<5; i3++) {
while(j3<5){
while (j<5){
for (i2=0;i2<5;i2++){
Total += Array[i][j]*Array2[i2][j2];
j++;
Array3[i3][j3]=Total;
}}
j=0;
j2++;
j3++;
Total=0;
}
i++;
j=0;
j2=0;
j3=0;
Total=0;
}
我的问题是:修改代码使其可以读取两个包含任意大小数组的 .txt 文件然后成功执行乘法的最简单方法是什么?
编辑我只能使用数组来做这件事,不幸的是我不能使用向量。
我认为涉及 new 运算符是否正确?
【问题讨论】:
-
使用
std::vector而不是裸数组。 -
事情是这是一个评估,他们告诉我们只使用数组
-
哎呀,你不认为你应该在你的帖子中包含这个限制吗?
-
@Paolokiller:所以写一些类似于
std::vector的东西(当它需要增长到超出其当前容量时重新分配和移动元素),然后使用它而不是裸数组。 (是的,这将涉及new和delete。您还应该阅读Rule of Three。指针杂耍很棘手,这就是为什么我们有像vector这样的友好图书馆设施来为我们管理它。) -
@Paolokiller:您的意思是您不能将数组包装在一个为您管理它的好类中?这是一个相当奇怪的约束。但如果情况确实如此,只需在一大堆未封装的代码中做同样的事情(分配一个更大的数组、移动数据并删除旧的)。
标签: c++ arrays multiplication