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

时间:2018-04-03 18:34:31

标签: c++ types char int 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;
    }

}

这是我的矩阵表示图类的成员函数部分。 矩阵是未加权有向图的邻接矩阵。 矩阵被动态分配为1-D阵列,并使用行主要顺序来访问所需的索引。

我试图获得如下所示的顶点来定义边缘:

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

时,我都会收到调试错误
  

运行时检查失败#3 - 正在使用变量'vertex2Index'而未初始化。

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

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

1 个答案:

答案 0 :(得分:0)

您可以按照评论中的建议使用cin.peek()。 不过,我觉得读入字符串会更简单,并使用stoi()。 顺便说一句,你有意不跳过最后一个条目(-1作为vertex1)??您的实施情况尚不清楚。

相关问题