程序的 substr() 函数中的输出出错
output coming wrong in substr() function of program
代码cout<< substr(temp,1,strlen(word)+1)<<'n';
的输出出错 数组 s 中最后一句的输出应该是 rockstar,但输出 rockstar r。
此外,输出的"没人敢"这句话也是错误的。它来的不是一只猫。猫怎么来而不是罐头。请说明导致此类问题的原因。
#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]!=' ')
{
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 样式字符串必须始终以零结尾 (' '
(。否则,它不是一个合适的字符串,并且没有太多工作。substr
函数似乎没有添加此终止符。
除此之外,对返回值使用静态缓冲区是非常危险的,因为每次调用substr
都会破坏以前的返回。在同一语句或多线程应用中使用两个调用将不起作用。
所有这些都可以通过使用std::string
来解决,它甚至有一个工作substr
成员函数。
相关文章:
- 递归函数计算序列中的平方和(并输出过程)
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 请解释"函数1(p1,p2,p3);"的输出
- 在C++目录中搜索文件的函数输出中出错
- 如果我决定输入 (1 2) 而它要求 x,为什么我的输出会出错,但如果我输入 (12) 工作正常
- 程序的 substr() 函数中的输出出错
- C++ 控制台输出到 cmd 在重复十次后出错
- 使用输出在声明容差范围内的EXPECT_NEAR时出错
- 我同时使用了莱布尼茨和瓦利斯公式来估算π但输出数字错误,我不知道我哪里出错了
- 尝试过载输出运算符时出错
- 输出出错
- C++:将自定义哈希键值从 unordered_map 输出到 std::cout 时出错
- 保护输入和输出文件描述符时出错
- 将字符指针(初始化为"\0")发送到标准输出是否出错?(C++)
- matPutVariable:尝试将数据输出到mat文件时出错(matrix::serialize::WrongSize
- 为什么我的输出流seg出错,而我的虚拟析构函数不起作用,但当我杀死虚拟的时候,它起作用了
- LNK2019输出运算符过载时出错
- 安装用C++编写的Python包(leven)时出错:g++无法识别的命令行选项--输出lib
- 创建输出文件 .rdstate() 时出错,返回值 2
- 在c++中编译Lex输出时出错