首页 > 解决方案 > 如何为多事的偶然事件添加 printf?

问题描述

显然,我需要解释我的意思,因为我真的不知道如何用这么几句话来描述这个场景。我正在尝试制作一个接收字符串和模式的程序,然后告诉用户在字符串中找到模式的偏移量以及次数。我坚持的部分是当模式出现不止一次时,它只输出它出现的最后一个偏移量

if(is_equal == 1)   //If string and pattern element are the same, Then declare at which offset
        {
            count++;
            if(count == 1)
            {
                sprintf(offset, "The pattern was found at offset %d", i);   //Prints the offset of the where the pattern appears in the string
                snprintf(full_message, sizeof full_message, "%s", offset);  //Redirects full_message to a buffer
            }
            else
            {
                sprintf(offset, " and %d", i);  //Repeats for every other instance of the pattern
                snprintf(full_message, sizeof full_message, "%s%s", full_message, offset);
            }
        }

如果我只有一种模式,这就是输出的样子

aerialsong@ubuntu:~$ ./m4p1
Please enter a number: 1234567890
Please enter a pattern: 34
The pattern was found at offset 2
The pattern was found 1 times

但如果碰巧不止一个:

Please enter a number: 123567123678
Please enter a pattern: 123
 and 6
The pattern was found 2 times

这里有什么问题?顺便说一句,我无法使用除 stdio.h 之外的任何库。那么这是否意味着 strcat 不在讨论范围内?

标签: c

解决方案


我认为这会有所帮助,您正在覆盖full_message,用于strcat附加(或您自己的strcat函数):

char* my_strcat(char* strg1, char* strg2)
{
    char* start = strg1;

    while (*strg1 != '\0')
    {
        strg1++;
    }

    while (*strg2 != '\0')
    {
        *strg1 = *strg2;
        strg1++;
        strg2++;
    }

    *strg1 = '\0';
    return start;
}

然后调用这个函数:

else
{
        sprintf(offset, " and %d", i);
        my_strcat(full_message, offset);

}

所以你刚刚使用了stdio.h库函数。


推荐阅读