skip to Main Content

I used Visual Studio.
The purpose of this code is to print the value that comes out when the received character arrangement is read vertically.

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>

int main(void) {
    int i, j;
    char a[5][15] = { 0, };
    for (i = 0; i < 5; i++) {
        for (j = 0; j < 15; j++) {
            scanf("%c", &a[i][j]); 
        }
    }

    for (i = 0; i < 15; i++) {
        for (j = 0; j < 5; j++) {
            printf("%c", a[j][i]);
        }
    }
    return 0;
}

input

AABCDD
afzz
09121
a8EWg6
P5h3kx

Expected Output

Aa0aPAf985Bz1EhCz2W3D1gkD6x

Real Output -> It doesn’t print something.

I don’t know why it isn’t work on my purpose.
Please, explain for me.

2

Answers


  1. Your code will try to fill all of the characters in your 5×15 array. You need to stop filling a line as soon as you see an end-of-line character:

        for (j = 0; j < 15; j++) {
            char c;
            scanf("%c", &c);
            if (c == 'n')
                break;
            else
                a[i][j] = c;
        }
    

    This is just to get you started. You should debug your code and fix the other problems.

    Login or Signup to reply.
  2. Doing a compilation of all the things you can do to improve it. This comes from the comments below the question.

    1. Various columns have between 4 and 6 characters while only expecting 15 characters when reading a column. You need to make sure it is standardized. Row two (2) has 4 characters, the third (3) row has 5 characters and rows one (1), four (4), five (5) have 6 characters. This means that there will likly leave null values in those positions.

    2. As the user Barmur link in the comments to another question shows, when using scanf() in C you need to add an infront of '%c'. It should look as follows scanf(" %c", a[j][i]); This will have it stop at the end of line and skip any spaces that exist.

    Edit:
    The code given by anatolyg is another solid solution to the second problem that I had mentioned above. You can use either solution.

    Edit 2:
    Eric made me realize that I confused which values was being used for rows vs columns. Updated the values so that it showed the correct ones.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search