【问题标题】:strange character is output to the terminal奇怪的字符输出到终端
【发布时间】:2020-06-28 16:48:26
【问题描述】:

我是 C/C++ 编程的初学者。 这是我在终端中按升序显示二进制数的程序(我正在 Linux Mint 中编译)。

#include <stdio.h>
#include <math.h>
#include <stdbool.h>
#include <string.h>

void reverse(char *x, int begin, int end)
{
   char c;

   if (begin >= end)
      return;

   c          = *(x+begin);
   *(x+begin) = *(x+end);
   *(x+end)   = c;

   reverse(x, ++begin, --end);
}


int main()
{
    unsigned int bitCount;
    unsigned int naborCount;

    printf("Число битов в наборе: ");
    scanf("%d", &bitCount);
    printf("\n");

    naborCount = pow(2, bitCount);

    char naborStr[bitCount*2];

    for(int i = 0; i<naborCount; i++)
    {
        for(int j = 0; j<bitCount; j++)
        {
            if((i & (1<<j))==0)
            {
                strcat(naborStr, "0 ");
            }
            else
            {
                strcat(naborStr, "1 ");
            }
            if(j == bitCount-1)
            {
                reverse(naborStr, 0, strlen(naborStr)-1);
                printf("%s \r\n", naborStr);
                memset(naborStr, 0, sizeof(naborStr));
            }
                
        }
    }
    
    return 0;
}

This is what I see in the terminal

这个符号是从哪里来的?如何解决?

【问题讨论】:

  • 这看起来像 C 代码,而不是 C++ 代码。为什么标记为c++
  • strcat 需要以 nul 结尾的参数,否则其行为未定义。
  • 抱歉,已修复
  • 欢迎使用 stackoverflow,请注意 here 不鼓励发布输出图像以及使用外部链接发布图像。
  • 看看下面的答案是否有帮助

标签: c linux string terminal


【解决方案1】:

C 字符串以 null 结尾。

%s 说明符搜索空终止符。

在你的情况下,它会一直打印直到找到一个,所以你会得到一些随机符号。

尝试在字符串末尾使用空字符并检查。

看看下面的实现:

#include <stdio.h>
#include <math.h>
#include <stdbool.h>
#include <string.h>

void reverse(char *x, int begin, int end)
{
char c;

if (begin >= end)
    return;

c          = *(x+begin);
*(x+begin) = *(x+end);
*(x+end)   = c;

reverse(x, ++begin, --end);
}


int main()
{
    unsigned int bitCount;
    unsigned int naborCount;

    printf("Число битов в наборе: ");
    scanf("%d", &bitCount);
    printf("\n");

    naborCount = pow(2, bitCount);

    char naborStr[bitCount*2 + 1]; //Increased size by 1 for null character

    for(int i = 0; i<naborCount; i++)
    {
        for(int j = 0; j<bitCount; j++)
        {
            if((i & (1<<j))==0)
            {
                strcat(naborStr, "0 ");
            }
            else
            {
                strcat(naborStr, "1 ");
            }
            if(j == bitCount-1)
            {
                reverse(naborStr, 0, strlen(naborStr)-1);
                naborStr[bitCount*2 +1] = '\0'; //Appending null character
                printf("%s \r\n", naborStr);
                memset(naborStr, 0, sizeof(naborStr));
            }
                
        }
    }
    
    return 0;
}

【讨论】:

  • 谢谢!我把 memset() 方法放到外循环的顶部,它起作用了!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-03
  • 2017-12-04
  • 2012-02-13
  • 2021-04-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多