从文件C ++中读取二进制字符数组

时间:2015-10-14 09:57:23

标签: c++ arrays

所以我需要从文件中读取一个网格,网格的宽度和长度总是一样的。问题是当我尝试在最后一行上播放它时,它只显示了大约一半。

#include <iostream>
#include <fstream>
#include <cstring>

using namespace std;
ifstream TestIn("test");


int main()
{

    char Grid[1000][1000],s[1000];

    int LungimeX,LungimeY,i,j;

    TestIn.getline(s,1000);
    //finding the length
    LungimeX=strlen(s);
    cout<<LungimeX<<endl;

    //finding the width
    while (!TestIn.eof()) {
        TestIn.getline(s,1000);
        LungimeY++;
    }
    cout<<LungimeY;

    //reset .eof
    TestIn.clear();
    TestIn.seekg(0, TestIn.beg);

    //get the grid into the array
    for(i=1;i<=LungimeY;i++) {
    for(j=1;j<=LungimeX;j++) {
        TestIn.get(Grid[i][j]);
    }}

    for(i=1;i<=LungimeY;i++){
    for(j=1;j<=LungimeX;j++){
        cout<<Grid[i][j];
    }}

    return 0;
}

所以是的,任何想法如何解决这个问题?

3 个答案:

答案 0 :(得分:0)

  1. LungimeY未初始化
  2. 需要在文件倒带后读取(跳过)标题行
  3. 填充数组后每行读取后需要跳过CR和/或LF字符

答案 1 :(得分:0)

你没有忽略换行符,LungimeX是不包括换行符的行长。一个简单的解决方案是,如果遇到换行符,则在读取文件时读取下一个字符。     #包括     #包括     #include

using namespace std;
ifstream TestIn("test");


int main()
{

    char Grid[1000][1000],s[1000];

    int LungimeX,LungimeY,i,j;

    TestIn.getline(s,1000);
    //finding the length
    LungimeX=strlen(s);
    cout<<LungimeX<<endl;

//finding the width
            while (!TestIn.eof()) {
                TestIn.getline(s,1000);
            LungimeY++;}
cout<<LungimeY;

//reset .eof
TestIn.clear();
TestIn.seekg (0, TestIn.beg);

//get the grid into the array
for(i=1;i<=LungimeY;i++){
for(j=1;j<=LungimeX;j++){
    TestIn.get(Grid[i][j]);
    if(Grid[i][j] == '\n') //check new line character
       TestIn.get(Grid[i][j]);
}}

for(i=1;i<=LungimeY;i++){
for(j=1;j<=LungimeX;j++){
    cout<<Grid[i][j];
}
cout<<endl;
}



    return 0;
}

是的请在C ++中使用0索引,这样就会浪费内存。

答案 2 :(得分:0)

这种更多的C ++方法怎么样?

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

int main()
{
    std::string fname("test.txt");
    std::ifstream f(fname.c_str());

    std::vector<std::string> lines;
    std::string line;
    while(std::getline(f, line))
        lines.push_back(line);

    unsigned long int num_rows = lines.size();
    unsigned long int num_cols = 0;
    if(num_rows > 0)
        num_cols = lines[0].length();

    std::cout << "num_rows = " << num_rows << std::endl;
    std::cout << "num_cols = " << num_cols << std::endl;

    for(unsigned long int i = 0; i < num_rows; ++i)
    {
        for(unsigned long int j = 0; j < num_cols; ++j)
            std::cout << lines[i][j];
        std::cout << std::endl;
    }

    return 0;
}