如何使用 cin 将输入的整数值转换为 char 类型变量?

How to get input integer value into char type variable using cin?

void defineEdge()
{
    char vertex1, vertex2;
    int charToInt = 0;

    while (charToInt != -1)
    {
        cout << "Define an edge by listing a pair of vertices (-1 to stop):  ";
        cin >> vertex1 >> vertex2;
        cin.ignore(256, '\n');
        charToInt = vertex1 - '0';

        // getVertexIndex() eventaully returns the index representing
        // [index of vertex1][index of vertex2] in 1-D array 
        // Assign 1 to represent the directed connection between 2 vertices 
        graphMatrix[getVertexIndex(vertex1, vertex2)] = 1;
    }

}

这是表示图 class 的矩阵的成员函数部分。 该矩阵是未加权有向图的邻接矩阵。 该矩阵被动态分配为一维数组,并使用行主要顺序来访问所需的索引。

我正在尝试获取如下所示的顶点来定义边:

Define an edge by listing a pair of vertices (-1 to stop): A B
Define an edge by listing a pair of vertices (-1 to stop): B A
Define an edge by listing a pair of vertices (-1 to stop): -1 A

但是,每当我输入 -1 时都会出现调试错误

Run-Time Check Failure #3-The variable 'vertex2Index' is being used without being initialized.

我想知道是否有正确的方法来获取整数值 (i.g.-1) 到 字符变量 (i.g.vertex1)

编辑:还有另一个用于存储顶点的整数列表,所以我想使用getVertexIndex() 获取vertex1 和vertex2 以获取相应索引的索引。

您可以按照评论中的建议使用cin.peek()。 尽管如此,我觉得读入字符串并使用 stoi() 会更简单。 顺便说一句,你是不是故意不跳过最后一个条目(-1 作为顶点 1)?这在您的实施中还不清楚。