问题
I'm new to C++, only been programming a few days so this might seem stupid, but can you spot why my arrays are not working correctly? This is the start of a program I'm designing that will solve Sudoku puzzles, but the 2D array that I'm using to solve it isn't working correctly.
#include <iostream>
#include <string>
using namespace std;
int main () {
char dash[9][9];
for (int array=0; array<9; array++) {
for (int array2=0; array2<9; array2++) {
dash[array][array2]=array2;
cout << dash[array][array2];
}
}
cout << dash[1][4] << endl; //This is temporary, but for some reason nothing outputs when I do this command.
cout << "╔═══════════╦═══════════╦═══════════╗" << endl;
for (int count=0; count<3; count++) {
for (int count2=0; count2<3; count2++) {
cout << "║_" << dash[count][count2*3] << "_|_" << dash[count] [count2*3+1] << "_|_" << dash[count][count2*3+2] << "_";
}
cout << "║" << endl;
}
cout << "╠═══════════╬═══════════╬═══════════╣" << endl;
for (int count=0; count<3; count++) {
for (int count2=0; count2<3; count2++) {
cout << "║_" << dash[count][count2*3] << "_|_" << dash[count] [count2*3+1] << "_|_" << dash[count][count2*3+2] << "_";
}
cout << "║" << endl;
}
cout << "╠═══════════╬═══════════╬═══════════╣" << endl;
for (int count=0; count<3; count++) {
for (int count2=0; count2<3; count2++) {
cout << "║_" << dash[count][count2*3] << "_|_" << dash[count][count2*3+1] << "_|_" << dash[count][count2*3+2] << "_";
}
cout << "║" << endl;
}
cout << "╚═══════════╩═══════════╩═══════════╝" << endl;
return 0;
}
Also I'm aware that there may be easier ways to build the Sudoku board, but I can already see in my mind how this one will work, and if it fails, well, the only way to learn is by failure. All I want to know is what is wrong with the arrays.
回答1:
You're trying to display chars as if they were integers. Well, technically, they are, but they don't display as integers. Either change your char array to an int array(very easy), or every time you display the data, cast it to int(tedious).
回答2:
You've got numeric data stored in your char
array, which is fine, but cout
tries to print it as a character. Try casting to integer during output:
cout << (int)dash[count][count2*3]
The other option is to store characters in the array:
for (int array=0; array<9; array++) {
for (int array2=0; array2<9; array2++) {
dash[array][array2] = '0' + array2;
}
}
回答3:
Change char dash[9][9]
to int dash[9][9]
. You assign small numbers to dash[i][j]
, as char
s they are mostly unprintable control characters, so nothing intelligible gets printed. As int
s they are printed as you expect.
来源:https://stackoverflow.com/questions/8692011/what-is-wrong-with-this-char-array-code