从文本文件中读取数据,分配数组和打印

时间:2015-04-23 21:10:56

标签: c++

只是一个免责声明:这个练习已经到期,我提出它不完整,但想跟进并理解我的错误。

要求是读取两个文本文件的内容,将它们的(浮点)值分配给2D矩阵,然后将它们打印到控制台。还有其他要求,但它们与手头的问题无关。

根据我的问题排查,读取这些文件时出现问题,或者打印方式有问题。

以下是每个文本文件的内容:

文件1:

81.51310482 91.38325441 27.8637468  96.53709795
90.6244833  63.26754258 54.715496   15.76918882
12.70503097 9.75891752  95.79855889 97.10780782

文件2:

80.69838114 90.46987855 27.58524858 95.57220941
89.71869137 62.63518334 54.16861448 15.61157574
12.57804415 9.661377115 94.84105205 96.13721503

这是我的代码:

#include<iostream>
#include<cmath>
#include<fstream>
#include<string>
#include<stdlib.h>
int r,ro,c,co,iter;
float ary,avg,a1[3][4],a2[3][4];

std::ifstream fs;
std::string line;
void assignarray(int iter,float ary);
void printarray(int iter);

int main(){
//select text files
for(iter=1;iter<3;iter++){
    if(iter==1){
        fs.open("table_1.txt");
        ary=a1[r][c];}
    else if(iter==2){
        fs.open("table_2.txt");
        ary=a2[r][c];}
if(fs.is_open()){
    //std::cout<<"File was successfully opened.\n";
    assignarray(iter,ary);
    printarray(iter);
    fs.close();}
else{
    std::cout<<"There was a problem opening or writing to the destination file, please try again.\n";
    return 1;}
    }
std::cout<<"Please input the coordinates for the row and column of both arrays, the entries of which will be averaged.\nInput format: R C\n";
std::cin>>ro>>co;
avg=(a1[ro][co]+a2[ro][co])/2;
std::cout<<"The average of the entries sharing coordinates Row "<<ro<<" and Column "<<co<<" is:"<<avg<<"\n";    
}

void assignarray(int iter,float ary){
while(std::getline(fs,line)){
    for(r=0;r<3;r++){//increment from row value 1 to 3
        for(c=0;c<4;c++){//increment column from 1 to 4
            fs>>ary;
            }
        }
    }
}
void printarray(int iter){//looks good
std::cout<<"table_"<<iter<<".txt contains the following values:\n";
    for(r=0;r<3;r++){
        for(c=0;c<4;c++){
            std::cout<<ary<<' ';
        }
    std::cout<<"\n";//line break after each row has been filled; creates columns
    }
}

以下是(错误的)输出的一部分:

table_1.txt contains the following values:
0 0 0 0
0 0 0 0
table_2.txt contains the following values:
6.58383e-039 6.58383e-039 6.58383e-039 6.58383e-039 
6.58383e-039 6.58383e-039 6.58383e-039 6.58383e-039 

我测试的部分是assignarray void函数的内部。到目前为止,我做了很多研究,但这是我第一次应用这些概念;它运作得不太顺利。让我知道你的想法,和/或我如何纠正这个问题。另外,如果有更多信息可以提供澄清,请告诉我。

感谢。

P.S。无论出于何种原因,我不应该使用C ++ 11或更新的版本。如果您的建议牢记这一点,我将不胜感激。

1 个答案:

答案 0 :(得分:1)

你说:

  

我测试的部分最多的是assignarray void函数的内部。到目前为止,我做了很多研究,但这是我第一次应用这些概念;它没有太顺利地运作。让我知道你的想法,和/或我如何纠正这一点。

您不清楚希望在此功能中完成什么。

它的发布方式是什么?

完全没有在函数中使用

iter。不清楚为什么将它作为输入参数。

ary作为值传递。您对ary所做的任何更改都只是本地更改。它对调用函数没有影响。

void assignarray(int iter, float ary){

读一行。如果读取一行成功,请进入循环。读取的行不在此函数的任何位置使用。出于所有实际目的,只读取并丢弃该行。

while(std::getline(fs,line)){

    for(r=0;r<3;r++){//increment from row value 1 to 3
        for(c=0;c<4;c++){//increment column from 1 to 4

使用嵌套for循环,您尝试读取3 x 4 == 12个数字 这些数字(如果它们存在于文件中)被读入变量,但只有最后一个成功读取的数字存储在ary中。其余的都丢失了。

            fs>>ary;
            }
        }
    }
}

此函数的唯一副作用是全局变量line具有while循环条件下最后一条成功读取行的内容。

读取并丢失输入的其余部分。

<强>更新

有一些事情需要修复才能使程序正常工作。

然后,有一些事情需要改变,以提高计划的质量。奇怪的是,这些更改将使程序更容易修复,使其正常工作。

  1. 尽可能避免使用全局数据。
  2. 使用更具描述性的变量名称 - array1代替a1
  3. for移除main循环,并将其替换为几个函数调用。
  4. 在某些运算符周围添加空格,以使代码更具可读性。
  5. 我可以看到main被压缩成以下内容:

    int main()
    {
        float array1[3][4], array2[3][4];
        char const* file1 = "table_1.txt"; 
        readDataFromFile(file1, array1, 3);
        printArray(file1, array1, 3);
    
        char const* file2 = "table_2.txt"; 
        readDataFromFile(file2, array2, 3);
        printArray(file2, array2, 3);
    
        printAverage(array1, array2);
        return;
    }
    

    readDataFromFile可以是:

    void readDataFromFile(char const* file, float array[][4], int rows)
    {
       // This avoid the global variable fs
       std::ifstream fs("table_1.txt");
       if ( fs )
       {
          for( int r = 0; r < rows; r++)
          {
             for(int c = 0; c < 4; c++)
             {
                if ( !(fs >> array[r][c] )
                {
                    // Add code to deal with error.
                }
             }
          }
       }
       else
       {
          // Deal with the error condition.
       }
    }
    

    printArray可以是:

    void printArray(char const* file, float array[][4], int rows)
    {
       // No need for global r and c
       std::cout << file << " contains the following values:\n";
       for( int r = 0; r < rows; r++)
       {
          for(int c = 0; c < 4; c++)
          {
             std::cout << array[r][c] <<' ';
          }
          std::cout << "\n";
       }
    }
    

    printAverage可以是:

    void printAverage(float array1[][4], float array2[][4])
    {
       // No need for global ro and co
       int ro, co;
       std::cout << "Please input the coordinates for the row and column of both arrays, the entries of which will be averaged.\nInput format: R C\n";
       std::cin >> ro >> co;
    
       // No need for global avg
       float avg = (array1[ro][co] + array2[ro][co])/2;
       std::cout
          <<"The average of the entries sharing coordinates Row " << ro
          << " and Column " << co << " is:" << avg << "\n";    
    }
    

    通过这些更改,您可以完全消除所有全局变量。并且程序应该易于理解并修复可能存在的任何问题。