【问题标题】:I'm trying to create a square for 2d array using the size of a string, but it's coming out rectangular我正在尝试使用字符串的大小为二维数组创建一个正方形,但它是矩形的
【发布时间】:2014-05-05 10:44:16
【问题描述】:

这个程序的工作原理是让用户输入文本,使用 ctrl-z 结束程序,然后程序将字符串放入一个正方形 2D 数组中,然后从左到右从上到下显示,然后再到顶部从左到右。不幸的是,它变成了矩形而不是正方形。

这是我的代码:

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

int main (int argc, char *argv[], char **env)
{
    string s ; s.clear() ;
    int c = cin.get() ;
    while (!cin.eof())
    {
        s += c ;
        c = cin.get() ;
    }

    for ( int i = 0 ; i < s.length() ; ++i)
    {
        if (!isalpha(s[i]))
        {
            s.erase(i,1) ; // removes non-alphanumeric characters
            --i ;
        }
    }

    int side = 1 ;
    while (side * side < s.length() )
    {
        ++side ;
    }

    cout << endl << side << endl;

    char block[side][side] ;
    int i = 0;
    for (int r=0; r<side; r++)    //This loops on the rows.
    {
        for(int c=0; c<side; c++) //This loops on the columns
        {
            block[r][c] = s[i];
            i++;
        }
    }

    cout << endl;

    for (int r=0; r<side; r++)    //This loops on the rows.
    {
        for(int c=0; c<side; c++) //This loops on the columns
        {
            cout << block[r][c];
        }
        cout << endl ;
    }

    cout << endl ;

    for (int c=0; c<side; c++)    //This loops on the columns.
    {
        for(int r=0; r<side; r++) //This loops on the rows.
        {
            cout << block[r][c];
        }
        cout << endl;

    }
    cout << endl;
    cout << s << endl ;
}

示例输入和输出:这是用于加密的示例文本

变成:Thisisasampletextforencryption

Thisis
asampl
etextf
orencr
yption

Taeoy
hstrp
iaeet
smxni
iptco
slfrn

它们应该是 6x6。相反,它们是 6x5 和 5x6。

【问题讨论】:

  • 请考虑字母本身不是正方形,而是矩形。
  • 最后一个循环交换循环变量但不交换索引。这不应该影响维度,但会影响值的输出顺序。
  • 交换是正确的,但尺寸不正确。示例:这是一个用于加密的示例文本:Thisisasampletextforencryption Thisis asampl etextf orencr yption Taeoy hstrp iaeet smxni iptco slfrn 它们应该是 6x6。相反,它们是 6x5 和 5x6。编辑:哇,这些 cmets 的格式都关闭了。
  • thisisasampletextforencryption 只有 30 个字符长。您如何预计这会占用 36 个字符 (6x6)?

标签: c++ arrays loops for-loop multidimensional-array


【解决方案1】:

在您的示例中,您提供 30 个字符的输入,但不知何故期望 36 个字符的输出 (6x6)。如果您提供额外的字符,您最终将在每个显示中获得部分最后一行/列。如果您提供 36 个字符的输入,您最终将得到一个完整的正方形用于输出。

您正在阅读超过输入末尾的内容,这是未定义的行为。你碰巧得到了不可打印的字符。你应该这样做:

for (int r=0; r<side; r++)    //This loops on the rows.
{
    for(int c=0; c<side; c++) //This loops on the columns
    {
        if (i < s.length())
        {
            block[r][c] = s[i];
        }
        else
        {
            block[r][c] = '*';  //or put anything else you want here
        }
        i++;
    }
}

【讨论】:

  • 有没有办法用随机字符填充空白处?
猜你喜欢
  • 2021-04-15
  • 2010-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-15
  • 1970-01-01
相关资源
最近更新 更多