创建一个程序来读取邻接矩阵,用它和顶点数创建一个图,然后使用必要的信息为 GraphViz 编写一个 .dot 文件。
每次我尝试运行该程序时,最后访问的字符串 fileNameX 变量总是损坏(变量 fileName[x] 周围的堆栈已损坏)。我不知道我做错了什么,也不知道为什么会这样,因为我以前从未遇到过这个错误。有什么想法吗?
次要注意的是,当我运行程序时,它不会在目录中创建或打开有问题的文件,但我认为这是这个问题的一部分。如果没有,请随时纠正我。
图类的主要函数和打印函数如下。
#include <fstream>
#include "graph.h"
#include "string"
using namespace std;
int main()
{
ifstream infile;
infile.open("input.txt");
char c;
int i, count = 0;
string fileName1 = "graph0.dot", fileName2 = "graph1.dot", fileName3 = "graph2.dot";
while (infile>>c)
{
bool adjacencies[10][10];
infile.get(c);
i = (int)c;
// Loops looking for 1s and 0s to "store" in adjacency matrix
for (int x = 0; x < i; x++)
{
for (int y = 0; y < i; y++)
{
infile.get(c);
while (c != '1' && c != '0')
infile.get(c);
if (c == '1')
adjacencies[x][y] = true;
else if (c == '0')
adjacencies[x][y] = false;
}
}
graph G(adjacencies, i);
if (count == 0)
G.GraphVizOut(fileName1);
else if (count == 1)
G.GraphVizOut(fileName2);
else if (count == 2)
G.GraphVizOut(fileName3);
count++;
}
system("pause");
return 0;
}
// Notes paths between vertices with "X -- Y" notation.
void graph::CreateEdges(std::ofstream &outfile)
{
// If matrix is symmetrical, graph is undirected
if (isSymmetrical == true)
{
for (int x = 0; x < VertCount; x++)
{
for (int y = x; y < VertCount; y++)
{
if (adjacency[x][y] == true)
outfile << x << " " << "--" << y << "\n";
}
}
}
// If matrix is not symmetrical, graph is directed
else
{
for (int x = 0; x < VertCount; x++)
{
for (int y = 0; y < VertCount; y++)
{
if (adjacency[x][y] == true)
outfile << x << " " << "--" << y << "\n";
}
}
}
return;
}
// Creates the file, writes header information, and then calls CreateEdges above necessary info write to it
void graph::GraphVizOut(std::string filename)
{
std::ofstream VizOut;
VizOut.open(filename);
VizOut << "// Trey Brumley \n";
VizOut << "// File created by C++ BST Project \n";
VizOut << "graph G { \n";
CreateEdges(VizOut);
VizOut << "} \n";
VizOut.close();
return;
}
最佳答案
infile.get(c);
i = (int)c;
这从文件中读取一个字符,并将其(通常为 ASCII)值 存储在 i
中。 ASCII 数字在 [48,57] 范围内,因此当您从 0
索引到 i< 时,越界写入您的
.adjacencies
数组
要快速修复它:转换 ASCII 值以使数字正确。
infile.get(c);
i = c - '0';
要正确修复它:只需让 std::istream
读取实际的 int
。
infile >> i
if(i < 1 || i > 10) {
// Invalid input !
}
为了防止它:使用 std::array
而不是 C 风格的数组。
std::array<std::array<bool, 10>, 10> adjacencies;
关于c++ - 变量 [string] 周围的堆栈已损坏 c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30077264/