我正在尝试将文件中的文本读入char的矩阵
我是这样做的:
char** crearMundo()
{
ifstream input("C:\\Users\\JhonAlx\\Desktop\\file.txt");
input >> filas;
input >> columnas;
filas += 2;
columnas += 2;
char** laberinto = crearMatriz(filas, columnas);
//Initial fill
for(int i = 0; i < filas; i++)
{
for(int j = 0; j < columnas; j++)
{
laberinto[i][j] = ' ';
}
}
//Next two loops will fill only borders
for(int i = 0; i < filas; i++)
{
laberinto[0][i] = '?';
laberinto[filas - 1][i] = '?';
}
for(int i = 0; i < columnas; i++)
{
laberinto[i][0] = '?'; //VS throws error in this line
laberinto[i][columnas - 1] = '?';
}
//Fill actual content of file, omitting borders
for(int i = 1; i < filas - 1; i++)
{
for(int j = 1; j < columnas - 1; j++)
{
input >> laberinto[i][j];
}
}
return laberinto;
}
今天早上我编程时,它很好,但现在它抛出了这个错误:
访问冲突读取位置0xFDFDFDFD
使用VS2012进行调试并查看Locals资源管理器,我在ifstream变量上获得了这个文本:
输入{_Filebuffer = {_ Set_eback = 0xcccccccc&lt; 读取字符时出错 。串GT; _Set_egptr = 0xcccccccc&lt; 读取字符串字符时出错。&gt; ...} } std :: basic_ifstream&gt;
任何帮助都会被贬低。
答案 0 :(得分:0)
替代方法 - 将文件读入字符串,然后使用c_str()获取char数组。 例如:
std::ifstream in("content.txt");
std::string contents((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
contents.c_str() // The char array
答案 1 :(得分:0)
在第一组和最后一组循环(双重嵌套循环)中,您的索引限制是相对于filas
然后columnas
设置的。但是,中间两个(设置边框)是不同的,可能是错误的。请注意4个连续循环使用的索引:
laberinto[0..filas-1][0..columnas-1] -- fill with ' ' (ok: filas, then columnas)
laberinto[0,filas-1][0..filas-1] -- first borders (bad: filas, then filas)
laberinto[0..columnas-1][0,columnas-1] -- second borders(bad: columnas, then columnas)
laberinto[0..filas-2][0..columnas-2] -- read from file(ok: filas, then columnas)
由于在边框循环中使用了错误的索引,导致错误的可能原因是超出了数组边界;可能的解决方法是纠正这一点。