arrayscstringchar

Logic error of string input and output in C


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.


Solution

  • Your code will try to fill all of the characters in your 5x15 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.