目标是找到两个 c 字符串之间的公共前缀(必须使用特定的函数标头)
Goal is to find common prefix between two c strings (must use specific function header)
我在主函数中调用函数时遇到问题
函数定义是常量字符,我正在使用无法传递的字符串 函数"char prefix[]"的最后一个定义不知道如何处理它
#include <iostream>
#include <string>
using namespace std;
void prefix(const char s1[], const char s2[], char prefix[]); //Don't know what's the use of char prefix[]
int main()
{
string s1;
string s2;
cout << "Enter two sentences to store in two different strings" << endl;
getline(cin, s1);
getline(cin, s2);
const char *char1 = &s1[0];
const char *char2 = &s2[0];
prefix(char1, char2, );
return 0;
}
void prefix(const char a[], const char b[], char prefix[])
{
int i = 0;
for (; a[i] != 0 /* not a null char */ && a[i] == b[i] /* chars are
equal */; ++i)
prefix[i] = a[i]; // copy char to prefix
prefix[i] = 0; // null terminate prefix
}
为前缀分配内存,并将指针传递给此内存:
#include <iostream>
#include <memory>
#include <string>
using std::cin;
using std::cout;
using std::getline;
using std::string;
void prefix(const char s1[], const char s2[], char prefix[]);
int main()
{
string s1;
string s2;
cout << "Enter two sentences to store in two different stringsn";
getline(cin, s1);
getline(cin, s2);
const char *char1 = &s1[0];
const char *char2 = &s2[0];
std::unique_ptr<char[]> p = std::make_unique<char[]>(std::min(s1.length(), s2.length()));
prefix(char1, char2, p.get());
cout << p.get();
return 0;
}
void prefix(const char a[], const char b[], char prefix[])
{
int i = 0;
for (; a[i] != 0 && a[i] == b[i]; ++i)
prefix[i] = a[i];
}
相关文章:
- "error: no matching function for call to"构造函数错误
- 什么时候调用组成单元对象的析构函数
- 继承函数的重载解析
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- C++模板来检查友元函数的存在
- 递归函数计算序列中的平方和(并输出过程)
- 如何在友元函数中使用静态成员而不添加前缀 [类名]::
- 目标是找到两个 c 字符串之间的公共前缀(必须使用特定的函数标头)
- 任何需要 std:: 前缀的函数
- 在C++中使用标准 C 函数时,是否需要"std::"前缀?
- C++成员函数定义类前缀快捷方式(也是模板)
- GCC 前缀增量运算符在将值传递给函数时行为异常
- 为什么命名空间中的某些函数可以在没有命名空间范围前缀的情况下访问
- C++后缀/前缀运算符重载作为非成员函数
- 派生类使用或不带 "virtual" 前缀重写基类的虚函数之间有什么区别?
- 在 CPP 文件中使用命名空间作为函数定义的前缀是否是一种好的做法
- 为什么某些 Boost 函数不需要以命名空间为前缀
- 函数调用的前缀"::"在C++中有什么作用?
- 构造函数定义是否可以以 "class" 关键字为前缀?
- 可能隐藏cv前缀的函数在OpenCV