C 如何为重大事件添加printf?

C 如何为重大事件添加printf?,c,C,显然,我需要解释我的意思,因为我真的不知道如何用这么少的话来描述这个场景。我试图制作一个程序,它接收一个字符串和一个模式,然后告诉用户在字符串中找到模式的偏移量,以及找到模式的次数。我被卡住的部分是当图案出现不止一次时,它只输出最后一次出现的偏移量 if(is_equal == 1) //If string and pattern element are the same, Then declare at which offset { count++;

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

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不在表中了?

我认为这会有所帮助,您正在覆盖
完整消息
,使用
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
库函数。

您覆盖了
full\u message
变量而不是附加到它。使用
strcat()
附加到字符串。这是否回答了您的问题?Do
snprintf(完整消息+strlen(完整消息),sizeof(完整消息)-strlen(完整消息),“和%d”,i)。你不能做
sprintf(buf,“%s”,buf)
,这是未定义的行为。如果我不能添加strcat,因为我只能使用stdio.h库怎么办?@AerialSong我为你的特例编辑了我的帖子。