简体   繁体   English

为什么我的程序不能从文件中将字符输入到2d数组中?

[英]Why isn't my program inputing chars into 2d array from file?

I'm trying to input chars into a 2d array from a file, but its not putting anything into the array. 我正在尝试将字符输入到文件中的二维数组中,但它没有将任何内容放入数组中。 When I try to print it out I just get a bunch of symbols that look like this - ╠ 当我尝试将其打印出来时,我会得到一堆看起来像这样的符号 - ╠

Here is an example that produces the same error: 这是一个产生相同错误的示例:

test file looks like this: 测试文件如下所示:

g g g g g g g g g g
g g g t t t t t t g
g g g t t g t t g g
g t t g g t g g t g
g t t g g t g g t g
g t g t t g t t g g
g t t g g t g g t g
g t t g g t g g t g
g t g t t g t t g g
g g g g g g g g g g

Example that produces same error: 产生相同错误的示例:

#include<iostream>
#include<string>
#include<fstream>

using namespace std;


int main() {
    ifstream inFile;
    char myArray[15][15];

    inFile.open("C:\test\Ch5p_fa.asc");

    int rows = 10;
    int columns = 10;

    for (int i = 0; i < rows; i++)
    {
        for (int j = 0; j < columns; j++) {
            inFile.get(myArray[i][j]);
        }
    }


    for (int i = 0; i < rows; i++)
    {
        for (int j = 0; j < columns; j++) {
            cout << myArray[i][j] << ' ';
        }
        cout << endl << endl;
    }

    inFile.close();

cin.get();

}

Your columns are two times smaller, as they dont account for white characters. 你的列要小两倍,因为它们不考虑白色字符。 You could write your first loop as follows for example, ising isalpha to check if your current character is alphanumeric: 你可以编写你的第一个循环,例如,ising isalpha来检查你当前的字符是否是字母数字:

char tmp;
for (int i = 0; i < rows; i++)
{
    for (int j = 0; j < columns*2; j++) {
        tmp = inFile.get();
        if (isalpha(tmp))
        {
            myArray[i][j/2] = tmp;
        }
    }
}

inFile.get(myArray[i][j]) will read all the characters, including spaces. inFile.get(myArray[i][j])将读取所有字符,包括空格。 Use the >> stream operator instead, this will skip the spaces: 使用>> stream运算符,这将跳过空格:

if (!inFile)
    return 0;

//initialize the array
memset(myArray, 0, 15 * 15);

for (int i = 0; i < rows; i++)
{
    for (int j = 0; j < columns; j++)
    {
        if (!(inFile >> myArray[i][j]))
        {
            //break the loop
            i = rows;
            break;
        }
    }
}

Try this: 尝试这个:

int main() {

    ifstream inFile;
    char myArray[15][15];

    inFile.open("C:\\test\\Ch5p_fa.asc", std::fstream::in);   // std::fstream::in allows you to read from the file.

    int rows = 10;
    int columns = 10;

    for (int i = 0; i < rows; i++)  {
        for (int j = 0; j < columns; j++) {
            inFile.get(myArray[i][j]);
            inFile.get();                       // Skeem unwonted char
        }
    }

    inFile.close();

    cin.get();

}

If you need the spaces just make column twice as big. 如果你需要空格,只需将列的两倍大。

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

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