繁体   English   中英

从文件C ++读取bidemensional char数组

[英]Reading bidemensional char array from file C++

所以我需要从文件中读取一个网格,网格的宽度和长度始终是相同的。问题是当我尝试在最后一行中对其进行标注时,它仅显示了一半。

#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;
}

是的,有什么办法解决此问题吗?

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

您并没有忽略换行符LungimeX是不包括换行符的行的长度。 一个简单的解决方案是在读取文件时遇到换行符时读取下一个字符。 #include #include #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索引,这是在浪费内存。

这种更多的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;
}

暂无
暂无

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

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