gpt4 book ai didi

C++ 程序返回数字而不是 Char

转载 作者:行者123 更新时间:2023-11-28 00:11:31 24 4
gpt4 key购买 nike

我无法弄清楚为什么下面的程序在执行时返回数字而不是 5 行 10 列的英镑符号。它似乎正在返回一个内存地址,但我不确定。基本上它吐出“52428”而不是英镑符号,但以 5 x 10 的正确模式。基本上我看到了这个:

52428524285242852428524285242852428524285242852428
52428524285242852428524285242852428524285242852428
52428524285242852428524285242852428524285242852428
52428524285242852428524285242852428524285242852428
52428524285242852428524285242852428524285242852428

代码如下:

#include <iostream>
using namespace std;

//Constants for Total Rows and Total Columns
static const unsigned short TOT_ROWS = 5, TOT_COLUMNS = 10;

//Function Prototypes
unsigned short convertChar(char);
bool isActive(unsigned short);
void initTheater(char[]);
void getTheater(char[]);
void updateheater(char[], unsigned short, unsigned short);
void storeTheater(char[]);

int main()
{
//Variable and Array Decs
char theater[TOT_ROWS][TOT_COLUMNS];
double price[TOT_ROWS];
char selection;

//Get price input per row
for (unsigned short rowNum = 0; rowNum < TOT_ROWS; rowNum++)
{
cout << "Enter the price for row " << rowNum+1 << ":";
cin >> price[rowNum];
}

//Initialize Theater
initTheater(*theater);

//Loop to wait for one of the exit commands
do
{
getTheater(*theater);
cout << "Enter a selection: ";
cin >> selection;
} while (isActive(selection));
return 0;
}

//Initalize theater by placing '#' in each array element
void initTheater(char theater[])
{
for (unsigned short rows = 0; rows < TOT_ROWS; rows++)
{
for (unsigned short cols = 0; cols < TOT_COLUMNS; cols++)
{
theater[rows][&cols] = '#';
}
}
}

//Display current state of theater
void getTheater(char *theater)
{
for (unsigned short viewRows = 0; viewRows < TOT_ROWS; viewRows++)
{
for (unsigned short viewCols = 0; viewCols < TOT_COLUMNS; viewCols++)
{
cout << theater[viewRows][&viewCols];
}
cout << endl;
}
}

//Update the Theater by placing a '*' or '#' in the specific row and seat.
void updateTheater(char *theater[], unsigned short row, unsigned short column)
{
//Expand to determine current state of array element and flip to the alternate
theater[row][column] = '*';
}

//Check if user has typed exit command and exit if yes
bool isActive(unsigned short selection)
{
if (selection == '9' || selection == 'q' || selection == 'Q')
{
return false;
}
return true;
}

最佳答案

数组根本不像您期望的那样工作。除了您需要了解数组在 C++ 中的工作原理并正确使用它们之外,没什么好说的。 (或使用 vector 或类似的东西。)

特别是,getTheaterinitTheater 函数不知道数组在内存中的布局方式。所以他们无法仅使用 [] 找到元素。

getTheater 中,您有这个:

        cout << theater[viewRows][&viewCols];

在 C 和 C++ 中,a[b][c] 等同于 *(*(a+b)+c)。所以上面等同于:

cout << *(*(theater + viewRows) + &viewCols);

重新排列:

cout << * (&viewCols + *(theater+viewRows));

这等同于:

char j = theater[viewRows];
cout << * (&viewCols + j);

因此,您正在查看内存中 viewCols 之后的内容,查看数组的错误元素以决定查看 viewCols 之后的距离。

关于C++ 程序返回数字而不是 Char,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32865981/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com