简体   繁体   English

C ++将数字从文本文件读入数组

[英]C++ reading numbers from a text file into an array

Hello i am student of the first year thats why i got problem with such easy task. 您好,我是第一年的学生,这就是为什么我遇到如此简单任务的问题。 I am working currently on matrix calculator but in the very begging i occured some problems with reading numbers from a text file and printing them on screen Here is my code: 我目前正在使用矩阵计算器,但是在乞求中,我从文本文件中读取数字并在屏幕上打印它们时出现了一些问题,这是我的代码:

#include <iostream>
#include <fstream>
#include <cstdlib>

using namespace std;
 int main()
{
    ifstream infile;
    infile.open("matrix.txt", ios::in);
    //check for an error
    if(infile.fail())
    {
        cerr<<"Error opening file";
        exit(0);
    }
    //char sign;
    int n = 0;
    double matrix[n];
    while(!infile.fail())
    {
        infile >> matrix[n];
        n++;
        //if(infile.eof()) {break;}
    }

infile.close();


    for(int i = 0;i<9;i++)
    {
        cout << matrix[i]<<endl;
    }
return 0;
}

In the shortcut about the whole program it is supposed to read from a text file and calculate a determinant of 2x2 matrix or 3x3 matrix. 在关于整个程序的快捷方式中,应该从文本文件中读取并计算2x2矩阵或3x3矩阵的行列式。 If you can give me any ideas which will be useful in the future for example how i can check if the line in text file ended i would be thankful. 如果您能给我提出任何对将来有用的想法,例如我如何检查文本文件中的行是否结束,我将不胜感激。 But mostly i want to know what i am doing wrong. 但大多数情况下,我想知道我在做什么错。 Thank's from above. 从上面谢谢。

Consider the following lines of your code. 考虑下面的代码行。

int n = 0;
double matrix[n];
while(!infile.fail())
{
    infile >> matrix[n];
    n++;
    //if(infile.eof()) {break;}
}

You will need to read the documentation of your compiler to find whether it supports variable length arrays. 您将需要阅读编译器的文档,以了解其是否支持可变长度数组。 They are not allowed in standard c++, so if you want your program to be portable, you will need to stop using them. 在标准c ++中不允许使用它们,因此,如果您希望程序具有可移植性,则必须停止使用它们。

Secondly, you allocate an array of size 0, which is not allowed (again, your compiler might allow it as a non-standard feature). 其次,分配一个大小为0的数组,这是不允许的(同样,编译器可能会将其作为非标准功能使用)。

Thirdly, if the size of matrix is n , then matrix[n] will overflow. 第三,如果matrix的大小为n ,则matrix[n]将溢出。

Fourthly, checking the fail bit before extracting the value with infile >> matrix[n] is a bad idea. 第四,在使用infile >> matrix[n]提取值之前检查失败位是一个坏主意。 At some point you'll want to actually figure out how many valid values you have read, you'll find that it's simpler to test whether the extraction succeeded, after the extraction. 在某个时候,您实际上想弄清楚已经读取了多少个有效值,您会发现在提取之后测试提取是否成功比较简单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM