【问题标题】:How to strcat with intervals in C++? [closed]如何在 C++ 中使用间隔进行 strcat? [关闭]
【发布时间】:2014-01-23 17:40:21
【问题描述】:

这是我的代码:

#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;
}

我有一些问题。如何修改它以获得输出的 s 字符串中单词之间的间隔?以及如何在我的输出开头摆脱尴尬的 50 行(字面意思)长奇怪的符号?

编辑:对不起。以为没关系。输入最多应为 20x20 的单词数组,每个单词不超过 9 个字符。输出应该是一个 s 字符串,它表示通过从左上角开始以顺时针螺旋方式读取数组形成的句子。问题是.. 我的输出开头有奇怪的符号,单词之间没有间隔。

【问题讨论】:

  • 请提供具体输入和预期输出。我们不能输入 20x20x10 次来测试您的程序。
  • 在 C++ 中,你会使用 std::string 而不是这种 C 风格的乱码。
  • 我编辑了我的原始帖子。对不起。

标签: c++ arrays string matrix strcat


【解决方案1】:

使用 C++ 而不是 C

由于您使用的是 C++,因此您应该使用 C++ 方式编写代码,使用 std::string。您的一个问题(未初始化的字符串)可以通过这种方式解决,因为在 C++ 中无法定义未初始化的字符串。


替换

#include <string.h>

通过

#include <string>

替换

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

std::string s;

替换

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

通过

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

如果你还想用 C

你必须初始化你的输出字符串:

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

未初始化的字符串通常包含垃圾,strcat 会添加而不是删除它。

另外,如果你想要分隔符,你应该明确编码; strcat 本身不添加任何分隔符:

strcat(s, ",");

【讨论】:

  • 非常感谢!我有另一个问题。如果您能回答或至少给我一个提示,我将不胜感激。从左上角开始顺时针读取数组相对容易,但我似乎不知道如何逆时针从右下角开始。
  • @user3213110 请将此作为单独的问题发布,以防止混淆
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-09-29
  • 1970-01-01
  • 2020-10-30
  • 2019-01-05
  • 1970-01-01
  • 2017-10-09
  • 2011-07-23
相关资源
最近更新 更多