0

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");
}
2
  • 1
    You didn't try it with int before attempting int [][], did you? Commented Apr 13, 2013 at 4:59
  • 3
    In addition to A being the wrong type, you are not assigning all the elements: for (int j=0; j<i; j++) --> for (int j=0; j<9; j++) Commented Apr 13, 2013 at 5:03

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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;

Comments

0

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

4 Comments

1) Why? How is that an improvement?
By the time i posted my answer the above two got posted, i personally like answer of @H2CO3 . Use of static_cast is always preferred and correct.
But on your first point. The meaning of A[i][j] = '_'; is clear. So why would you replace it with A[i][j] = 95; which will just make the people reading your code wonder why? (and is theoretically less portable)
Agree. I didn't thought about portability. +1 for that. Was taught to assign like data types. Edited the answer. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.