sis007
sis007

Reputation: 51

Using ASCII characters in C++ program

I've been trying to print out _ <------ this character in a 2D array... But when I

tried compiling the code, it returned some garbage numbers. I think I'm doing something wrong... can anyone please help me out to solve this problem ?

void main (){

    int A[9][9];

    for (int i=0; i<9; i++){
        for (int j=0; j<i; j++){
            A[i][j]= '_';//I am doing this part wrong. 
        }

    }

    for (int r=0; r<9; r++) {
        for (int c=0; c<9; c++)
            cout << setw(3) << A[r][c];
        cout << endl;
    }

    system("pause");
}

Upvotes: 0

Views: 2181

Answers (3)

LionsDen
LionsDen

Reputation: 593

1. Assign the ASCII value to integer array rather than '_'. It will work even without change; but i feel it looks cleaner.

    A[i][j]= 95; // try this instead of '_'

  1. While printing, cout can print any data type without casting, but since we are looking for character to be printed, try explicit conversion.

    cout << setw(3) << char(A[r][c]);
    
  2. Not sure about the compiler you are using, but its a better practice to initialize the array to avoid garbage value tampering with your output

Upvotes: 0

user529758
user529758

Reputation:

The std::cout::operator<< operator is overloaded for several data types in order to facilitate (automagically-)formatted output. If you feed it an int, then it will print a number. If you give it a char, it will try to print it as a character. So either declare your array as an array of char, or cast the array member when printing:

cout << static_cast<char>(array[i][j]) << endl;

Upvotes: 1

Superman
Superman

Reputation: 3083

A is an int array. So cout would try to print an integer. Try cout << char(A[r][c]);

Upvotes: 1

Related Questions