【问题标题】:convert cin after input输入后转换cin
【发布时间】:2016-02-15 20:17:57
【问题描述】:

我正在尝试使用矩阵创建井字游戏,如果我让用户将每个位置输入为 [0][0] 或 [1][2] 等,它运行良好。但是,我希望用户能够输入“a、b、c”和“1、2、3”,但是当我尝试更改输入值并在控制台中输入字母时,我得到:

ConsoleApplication3.exe 中 0x01294C54 处未处理的异常: 0xC0000005:访问冲突读取位置0x345D4330。

有没有办法在不发生这种情况的情况下更改用户的输入值?

这是第一部分的代码,问题出在 Input 函数中。

#include <iostream>
#include <ctime>
using namespace std;

char matrix[3][3] = { '-', '-', '-', '-', '-', '-', '-', '-', '-' };

void Draw()
{
    cout << "  a b c" << endl;
    int row=1; 
    for (int i = 0; i < 3; i++)
    {
        cout << row << " ";
        for (int j = 0; j < 3; j++)
        {
            cout << matrix[i][j] << " ";
        }
        cout <<endl;
        row++;
     }
}

void Input()
{
    int pos1, pos2;
    cout << "Pick a place to put your X" << endl;
    cin >> pos1 >> pos2;
    if (pos1 == 'a')
        pos1 = '0';
    if (pos1 == 'b')
        pos1 = '1';
    if (pos1 == 'c')
        pos1 = '2';
    if (pos2 == '1')
        pos2 = '0';
    if (pos2 == '2')
        pos2 = '1';
    if (pos2 == '3')
        pos2 = '2';

    if (matrix[pos1][pos2] != 'O' && matrix[pos1][pos2] != 'X')
    {
        matrix[pos1][pos2] = 'X';
    }
}

【问题讨论】:

  • 您在哪里处理逗号分隔符,您认为将a 读入int 会如何工作?不成功的流提取将导致 pos1pos2 在 c++11 之前的代码中未初始化。这可能会发生在这里。
  • 除此之外,如果你将pos1pos2更改为char'0'不是0而是48'1'不是1而是@ 987654334@,等等...这是一个超出范围的访问。

标签: c++ cin


【解决方案1】:

您正在使用越界索引访问matrix。访问matrix 的有效索引是matrix[0][0]matrix[2][2]。您正在使用字符'0''1''2' 来访问矩阵。如果您的系统使用 ASCII 编码,它们的数值是 48、49 和 50。

此外,当您的变量类型为 int 并且您使用:

cin >> pos1;

程序将无法正确读取输入a。你需要使用:

char pos1;
cin >> pos1;

接受a 作为有效输入。

这是你的函数的修改版本:

void Input()
{
    char c1, c2;
    int pos1, pos2;

    cout << "Pick a place to put your X" << endl;
    cin >> c1 >> c2;

    if (c1 == 'a')
        pos1 = 0;
    else if (c1 == 'b')
        pos1 = 1;
    else if (c1 == 'c')
        pos1 = 2;
    else
    {
       // Error do something
    }

    if (c2 == '1')
        pos2 = 0;
    else if (c2 == '2')
        pos2 = 1;
    else if (c2 == '3')
        pos2 = 2;
    else
    {
       // Error do something
    }

    if (matrix[pos1][pos2] != 'O' && matrix[pos1][pos2] != 'X')
    {
        matrix[pos1][pos2] = 'X';
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-12
    • 1970-01-01
    • 2014-11-29
    • 1970-01-01
    • 2021-02-26
    • 2017-05-03
    相关资源
    最近更新 更多