سؤال

So here's my code:

#include <iostream>
#include <string.h>
using namespace std;

const int MAX_SIZE1 = 20;
const int MAX_SIZE2 = 10;

int main()
{
    char a[MAX_SIZE1][MAX_SIZE1][MAX_SIZE2];
    int n, i, j;
    cin >> n;
    for (i = 0; i < n; i++)
        for (j = 0; j < n; j++)
            cin >> a[i][j];

    char s[MAX_SIZE1 * MAX_SIZE1 * (MAX_SIZE2 - 1) + 1];
    int hor = 0, vert = 0;
    while (hor < n / 2 && vert < n / 2)
    {
        for (i = vert; i < n - vert; i++)
            strcat(s, a[hor][i]);
        for (i = hor + 1; i < n - hor; i++)
            strcat(s, a[i][n - vert - 1]);
        for (i = n - vert - 2; i >= vert; i--)
            strcat(s, a[n - hor - 1][i]);
        for (i = n - hor - 2; i > hor; i--)
            strcat(s, a[i][vert]);
        hor++;
        vert++;
    }
    if (n % 2)
        for (i = vert; i < n - vert; i++)
            strcat(s, a[hor][i]);
    else
        for (i = hor; i < n - hor; i++)
            strcat(s, a[i][vert]);
    cout << s << endl;
    return 0;
}

I've got some questions. How to modify it in order to get intervals between the words in the outputted s string? And how to get rid of the awkward 50 rows (literally) long weird symbols in the beginning of my output?

EDIT: I'm sorry. Thought it didn't matter. The input should be a maximum of 20x20 array of words which do not exceed 9 characters each. The output should be an s string which represents a sentence formed by reading the array in a clockwise spiral beginning from the top left corner. Problem is.. I got weird symbols in the beginning of my output and get no intervals between the words.

هل كانت مفيدة؟

المحلول

Use C++ instead of C

Since you are using C++, you should really write your code in a C++ way, using std::string. One of your problems (uninitialized string) can be fixed this way, since it is impossible to define an uninitialized string in C++.


Replace

#include <string.h>

by

#include <string>

Replace

char s[MAX_SIZE1 * MAX_SIZE1 * (MAX_SIZE2 - 1) + 1];

By

std::string s;

Replace

strcat(s, a[hor][i]);

by

s = s + a[hor][i];

If you still want to use C

You have to initialize your output string:

char s[MAX_SIZE1 * MAX_SIZE1 * (MAX_SIZE2 - 1) + 1] = "";

Uninitialized strings typically contain rubbish, and strcat adds to it, rather than removing it.

In addition, if you want delimiters, you should code that explicitly; strcat doesn't add any delimiters itself:

strcat(s, ",");
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top