gpt4 book ai didi

c++ - 尝试一次读取一个字符的字符矩阵

转载 作者:行者123 更新时间:2023-11-27 23:47:53 25 4
gpt4 key购买 nike

我正在尝试读取以下输入并将矩阵从输入分配给 char 矩阵。问题是,当我输出矩阵时,它以一种奇怪的方式输出字符。我做错了什么?

输入:

10 10
PPPPPPPPPP
PXXXXTPXXP
PXPPPPXXXP
PXXXPJPPXP
PPPXPXXXXP
CXXXXXPXPP
PXPXXXPXXP
PXPPPPPXXP
PXXXXXXXXP
PPPPPPPPPP

我的代码:

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
ifstream in("tom.in");
ofstream out("tom.out");
int n, m;
char s[101][101];
in>>n>>m; //read the size of the matrix
for(int i = 1; i<=n; i++)
for(int j = 1; j<=m; j++)
in.get(s[i][j]); //assign each element from the file to the matrix

for(int i = 1; i<=n; i++)
{
out<<endl;
for(int j = 1; j<=m; j++)
out<<s[i][j];
}

return 0;
}

输出:

PPPPPPPPP
P
PXXXXTPX
XP
PXPPPPX
XXP
PXXXPJ
PPXP
PPPXP
XXXXP
CXXX
XXPXPP
PXP
XXXPXXP
PX
PPPPPXXP
P
XXXXXXXXP

我使用的IDE是Codeblocks。

最佳答案

替换

in.get(s[i][j]); 

in >> s[i][j];

解释:

让我们通过打印出读取的内容来了解​​发生了什么,但作为数字,我们可以与 ASCII 表进行比较:

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
ifstream in("tom.in");
ofstream out("tom.out");
int n, m;
char x;
in>>n>>m; //read the size of the matrix
for(int i = 1; i<=n; i++)
{
for(int j = 1; j<=m; j++)
{
in.get(x);
cout << (int)x << ' ';
}
cout << '\n';
}
return 0;
}

这导致

10 80 80 80 80 80 80 80 80 80 80 10 80 88 88 88 88 84 80 88 88 80 10 80 88 80 80 80 80 88 88 88 80 10 80 88 88 88 80 74 80 80 88 80 10 80 80 80 88 80 88 88 88 88 80 10 67 88 88 88 88 88 80 88 80 80 10 80 88 80 88 88 88 80 88 88 80 10 80 88 80 80 80 80 80 88 88 80 10 80 88 88 88 88 88 88 88 88 80 10 

Right off the bat we have a 10. That doesn't map to a latin character like P, T, J, or X. It's a '\n'. A newline.

Checking the documentation for std::istream::get we find get is an unformatted input function. It is not stripping out whitespace for you the way you may be used to.

We can add some code to strip out the line endings, but why bother? A formatted input function will do that for us.

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
ifstream in("tom.in");
ofstream out("tom.out");
int n, m;
char x;
in>>n>>m; //read the size of the matrix
for(int i = 1; i<=n; i++)
{
for(int j = 1; j<=m; j++)
{
in >> x; // MADE CHANGE HERE
cout << (int)x << ' ';
}
cout << '\n';
}
return 0;
}

现在输出看起来像

80 80 80 80 80 80 80 80 80 80 80 88 88 88 88 84 80 88 88 80 80 88 80 80 80 80 88 88 88 80 80 88 88 88 80 74 80 80 88 80 80 80 80 88 80 88 88 88 88 80 67 88 88 88 88 88 80 88 80 80 80 88 80 88 88 88 80 88 88 80 80 88 80 80 80 80 80 88 88 80 80 88 88 88 88 88 88 88 88 80 80 80 80 80 80 80 80 80 80 80 

当转换回 ASCII 字符时,这是预期的

PPPPPPPPPPPXXXXTPXXPPXPPPPXXXPPXXXPJPPXPPPPXPXXXXPCXXXXXPXPPPXPXXXPXXPPXPPPPPXXPPXXXXXXXXPPPPPPPPPPP

关于c++ - 尝试一次读取一个字符的字符矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49099128/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com