从文本文件中读取时出错

时间:2015-09-14 12:38:55

标签: c++

我正在尝试编写一个能够从txt文件(Task)读取数据的代码。我做到了,但问题是结果不如预期,因为

at={3,5,7,10,15} 
bt={2,6,8,16,22}!!! 

代码是:

#include <iostream>
#include <fstream>
using namespace std;
void two_arrays_txt_file(float at[5], float bt[5], float zt[], float mt[]);
int main(int argc, char* argv[]) {
    float zt[5]; // the result value 
    float mt[5];
    float at[5];
    float bt[5];
    ifstream fin;
    fin.open("2arrays.txt");
    two_arrays_txt_file(at, bt, zt, mt);
    printf("(with a function  two ararays from txt file) \n adding z1 = %8.2f, z2 = %8.2f\t,z3=%f\t,z4=%f \tk=%f\n", zt[0], zt[1], zt[2], zt[3], zt[4]);
    printf("(with a function of productof two ararays from txt file) \n Multiplying mm1 = %8.2f, mm2 = %8.2f, mm3 = %8.2f, mm4 = %8.2f, mm5 = %8.2f", mt[0], mt[1], mt[2], mt[3], mt[4]);
    fin.close();
    cout << "Press Enter to Continue";
    getchar();
}
void two_arrays_txt_file(float at[5], float bt[5], float zt[], float mt[]) { // Task 6
    int i;
    for (i = 0; i<5; i++) {
        zt[i] = at[i] + bt[i];
        mt[i] = at[i] * bt[i];
    }
}

2 个答案:

答案 0 :(得分:0)

您没有从此处显示的代码段中的文件中读取任何内容。 in.open()只会打开文件。你需要阅读它

您可以通过&gt;&gt;'变量名'

来完成

答案 1 :(得分:0)

我不确定你的文本文件是怎么回事,但你不是从正在打开文本文件并关闭它的文本文件中读取任何内容。 在这里你应该做什么

 #include <iostream>
  #include <fstream>
 using namespace std;
void two_arrays_txt_file(float at[5], float bt[5], float zt[], float mt[]);
int main(int argc, char* argv[]) {
    float zt[5]; // the result value 
   float mt[5];
   float at[5];
   float bt[5];
   ifstream fin;
   fin.open("2arrays.txt");
   fin>>at[1] ;//  //you have to take input from file like this
   /* since i dont know that in what way numbers are stored in file so i        cannot tell you the exact way to take input and get output the way you want it.*/
two_arrays_txt_file(at, bt, zt, mt);
printf("(with a function  two ararays from txt file) \n adding z1 = %8.2f, z2 = %8.2f\t,z3=%f\t,z4=%f \tk=%f\n", zt[0], zt[1], zt[2], zt[3], zt[4]);
printf("(with a function of productof two ararays from txt file) \n Multiplying mm1 = %8.2f, mm2 = %8.2f, mm3 = %8.2f, mm4 = %8.2f, mm5 = %8.2f", mt[0], mt[1], mt[2], mt[3], mt[4]);
fin.close();
cout << "Press Enter to Continue";
getchar();
 }
void two_arrays_txt_file(float at[5], float bt[5], float zt[], float mt[]) {       
 int i;
 for (i = 0; i<5; i++) {
     zt[i] = at[i] + bt[i];
     mt[i] = at[i] * bt[i];
 }

}