use*_*980 7 c++ expression compiler-errors
请帮忙。我遇到很多错误。
sub2.cpp:在函数'int main()'中:sub2.cpp:11:14:错误:从'const char *'到'char'的无效转换[-fpermissive] sub2.cpp:12:14:错误:无效从'const char *'到'char'的转换[-fpermissive] sub2.cpp:16:17:错误:'const'之前的预期主表达式sub2.cpp:16:36:错误:'const之前的预期的主表达式'sub2.cpp:11:6:警告:未使用的变量'外部'[-Wunused变量] sub2.cpp:12:6:警告:未使用的变量'内部'[-Wunused变量] make:* [sub2]错误1个
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
char *Subtract(const char *outer, const char *inner);
int main()
{
char outer = "Bookkepper";
char inner = "keep";
char *word = new char[50];
word = Subtract(const char &outer, const char &inner);
cout << word << endl;
return 0;
}
char *Subtract(const char *outer, const char *inner)
{
int olen = strlen(outer);
int first_occ_idx = -1;
for(int i=0; i < olen; i++){
if(strncmp(outer+i, inner,strlen(inner)) == 0){
first_occ_idx = i;
}
}
if(first_occ_idx == -1){
return NULL;
}
int ilen = strlen(inner);
int xx = olen - ilen;
char *newstr = new char[xx];
int idx = 0;
for(int i=0; i < first_occ_idx; i++){
newstr[idx++] = outer[i];
}
for(int i=first_occ_idx+ilen; i < olen; i++){
newstr[idx++] = outer[i];
}
newstr[idx] = '\0';
return newstr;
}
Run Code Online (Sandbox Code Playgroud)
"Bookkepper" 在 C++ 中,像(sic)这样的字符串文字是const字符指针,它比 C 中严格一点。所以应该是:
const char *outer = "Bookkeeper"; // Note also spelling
Run Code Online (Sandbox Code Playgroud)
而不是:
char outer = "Bookkepper";
Run Code Online (Sandbox Code Playgroud)
此外,调用函数时不包含类型,因此:
word = Subtract(const char &outer, const char &inner);
Run Code Online (Sandbox Code Playgroud)
会更好:
word = Subtract(outer, inner);
Run Code Online (Sandbox Code Playgroud)
单独地(这些只是样式建议),表示大小(例如字符串中的字符数)的事物的正确类型是size_t而不是int。
显式清理所有动态内存通常被认为是一种很好的形式,因此,在从 返回之前main(),您可以输入:
delete[] word;
Run Code Online (Sandbox Code Playgroud)