c - 如何为多事的偶然事件添加 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 不在讨论范围内?
解决方案
我认为这会有所帮助,您正在覆盖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
库函数。
推荐阅读
- date - 如何使用应用脚本将日期插入谷歌标题?
- flutter - 在颤动中扩展时如何在screenView中保留扩展的小部件
- css - 如何在 Python Selenium 中使用 css 或运算符
- service-worker - 如何使用 Workbox-build 为 Service Worker 生成带有版本控制的预定义清单
- unity3d - Unity,如何使摩擦与运动一起工作
- javascript - 无法远程使用“three.js”库
- django - django静态文件突然消失404错误
- android - RangeError:颤动图像压缩问题
- curl - 如何使用 curl 将图像上传到 imgur.com 中的帐户?
- arrays - 如何更新 mongodb douments 中的文档数组?蒸汽 4,MongoKitten