简体   繁体   English

从C ++中的文件加载到2D数组中

[英]loading into 2d array from file in c++

I am having trouble reading numbers from a file into a 2d array in c++. 我在将文件中的数字读取到c ++中的2d数组时遇到麻烦。 It reads the first row just fine but the rest of the rows are populated with 0's. 它读取的第一行很好,但其余行都填充了0。 I have no idea what I'm doing wrong. 我不知道我在做什么错。

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    int myarray[20][20];

    int totRow = 20, totCol = 20, number, product, topProduct = 0, row, col, count;
    char element[4];

    ifstream file;

    file.open( "c:\\2020.txt" );

    if( !file )
    {
        cout << "problem";
        cin.clear();
        cin.ignore(255, '\n');
        cin.get();

        return 0;
    }

    while( file.good())
    {
        for( row = 0; row < totRow; row++ )
        {
            for( col = 0; col < totCol; col++ )
            {
                file.get( element, 4 );
                number = atoi( element );
                myarray[row][col] = number;
                cout << myarray[row][col] << " ";
            }
            cout << endl;

        }
        file.close();
    } 

If there are only numbers in your file, you can just read them with the >> operator. 如果文件中只有数字,则可以使用>>运算符读取它们。 Change your inner loop to: 将内部循环更改为:

for( col = 0; col < totCol; col++ )
{
    file >> myarray[row][col];
    cout << myarray[row][col] << " ";
}

The problem with file.get() is, it doesn't read beyond newline \\n . file.get()的问题在于,它不会读到换行符\\n See: std::basic_istream::get 参见: std :: basic_istream :: get

You're closing the file inside the while loop: 您正在while循环中关闭文件:

while( file.good())
    {
        for( row = 0; row < totRow; row++ )
        {
            for( col = 0; col < totCol; col++ )
            {
                file.get( element, 4 );
                number = atoi( element );
                myarray[row][col] = number;
                cout << myarray[row][col] << " ";
            }
            cout << endl;

        }
        file.close();   // <------ HERE
    } // end of while loop is here

You obviously can't read from a closed stream. 您显然无法从封闭的流中读取内容。 Now, because you're trying to read all the data in the first iteration of the while loop, this doesn't seem to be your immediate problem. 现在,由于您正在尝试在while循环的第一次迭代中读取所有数据,因此这似乎不是您的紧迫问题。 Note however, that the stream can still be good() even after you've read all the meaningful data (for example if there's a traling new-line character) and in that case, you'll enter the loop for the second time. 但是请注意,即使您已经读取了所有有意义的数据(例如,如果有一个换行的换行符),流仍然可以是good() ,在这种情况下,您将第二次进入循环。 That's a bug. 那是个错误。

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

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