c++ - 程序的 substr() 函数中的输出出错
问题描述
输出代码错误cout<< substr(temp,1,strlen(word)+1)<<'\n';
数组 s 中最后一句的输出应该是 rockstar,但输出的是 rockstar r。
此外,“没人敢”这句话的输出也是错误的。它来了没有一只猫。cat iscoming而不是can。请提出导致此类问题的原因。
#include<iostream>
#include<string.h>
using namespace std;
int par(char s[][80],int,int,char []);
char* substr(char*,int,int);
int main()
{
char s[][80]={{"this is rockstar"},{"I am rockstar"},{"the best one"},{"no one can dare"},{"rockstar rocks always"}};
char word[80]={"rockstar"};
int n1=5;
int num1=0;
cout<<par(s,n1,num1,word);
return 0;
}
int par(char s[][80],int n1,int num1,char word[80])
{
int k=0;
int length_word=strlen(word);
int t=0;
char beg[80];
while(t!=strlen(word))
{
beg[t]=word[t];
t++;
}
beg[t]=' ' ;
char end[80];
char mid[80];
mid[0]=' ';
t=0;
int l=1;
while(t!=strlen(word))
{
mid[l]=word[t];
l++;
t++;
}
mid[l]=' ';
t=0;
l=1;
end[0]=' ';
while(t!=strlen(word))
{
end[l]=word[t];
t++;
l++;
}
char temp[80];
while(k<=n1-1)
{
int i=0;
while(s[k][i]!='\0')
{
temp[i]=s[k][i];
i++;
}
if(strcmp(substr(temp,1,strlen(word)),beg)==0)
{
num1+=1;
}
cout<<substr(temp,1,strlen(word)+1)<<'\n';
cout<<beg<<" hello"<<'\n';
int tr;
for(tr=2;tr<strlen(temp)-(strlen(word)+2);tr++)
{
if(strcmp(substr(temp,tr,strlen(word)+2),mid)==0)
{
num1+=1;
}
}
if(strcmp(substr(temp,strlen(temp)-strlen(word),strlen(word)+1),end)==0)
{
num1+=1;
}
k++;
}
return num1;
}
char* substr(char *s,int i, int j)
{
int pos=i-1;
static char res[80];
int k=0;
while(pos<=i+j-2)
{
res[k]=s[pos];
pos++;
k++;
}
return res;
}
解决方案
C 风格的字符串必须始终以零结尾 ( '\0'
)。否则,它不是一个合适的字符串,也不会为它工作太多。该substr
函数似乎没有添加此终止符。
除此之外,使用静态缓冲区作为返回值是非常危险的,因为每次调用substr
都会破坏先前的返回值。在同一语句或多线程应用程序中使用两个调用将不起作用。
所有这些都可以通过 using 来解决std::string
,它甚至还有一个工作substr
成员函数。
推荐阅读
- android - getContentResolver 上不存在 Android _data'
- angular - 将 Angular 5 升级到 9 时出现“不兼容的对等依赖”错误
- javascript - 如何从选定的 Kendo Grid 行中填充表单
- python - 使用来自 spotify API 的 pandas 构建去规范化数据框的最佳方法
- mysql - 无论行是否更新,如何在 UPDATE 语句中输出列
- r - 按ID合并了两个数据集,现在观察多了
- angular - 为什么数组在Angular中意外更改
- cross-platform - 在 Ubuntu 上制作一个在 Mac 上运行的 python 可执行文件
- vuetify.js - 自定义 vuetify 数据表分隔符
- android - Flutter 滚动问题 - A RenderFlex 底部溢出 192 像素