[英]Reading bidemensional char array from file C++
So I need to read a grid from a file,the grid's width and lengths is always the same.The problem is when I try to cout it on the last line it only shows about a half of it. 所以我需要从文件中读取一个网格,网格的宽度和长度始终是相同的。问题是当我尝试在最后一行中对其进行标注时,它仅显示了一半。
#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;
}
So yeah,any ideas how to fix this? 是的,有什么办法解决此问题吗?
You were not ignoring the newline character LungimeX is the length of the line not including the new line character. 您并没有忽略换行符LungimeX是不包括换行符的行的长度。 a simple solution could be when reading the file if newline character is encountered read the next character. 一个简单的解决方案是在读取文件时遇到换行符时读取下一个字符。 #include #include #include #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;
}
And yes Please use 0 indexing in C++ you are wasting memory this way. 是的,请在C ++中使用0索引,这是在浪费内存。
What about this kind of more C++ approach ? 这种更多的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.