如何使用CIN将输入整数值获取到char类型变量中

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

本文关键字:获取 char 类型变量 整数 何使用 CIN 输入      更新时间:2023-10-16
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数组,并使用行主要顺序访问所需的索引。

我试图获得下面的顶点来定义边缘:

通过列出一对顶点(-1停止(来定义边缘:A B通过列出一对顶点(-1停止(来定义边缘:b a通过列出一对顶点(-1停止(来定义边缘:-1 A

但是,每当我输入-1

时,我都会出现调试错误

运行时检查失败#3-the变量'vertex2Index'正在不被初始化。

我想知道是否有适当的方法可以获取整数值(I.G. -1(char变量(i.g. vertex1(

编辑:还有另一个用于存储顶点的整数列表,因此我想获得Vertex1和vertex2,以使用GetVertexindex((获得相应索引的索引。

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