输出最长公共前缀#include<iostream> #include<cstring> using namespace std; string func(string s1,string s2) { char *p=s1; int a=strlen(s1)>strlen(s2)?strlen(s1):strlen(s2); for(int i=0;i<a;i++) { if(s1[i]==s2[i]) p++; else break; } return p; } int main() { int n; cin>>n; string s1,s2; cin>>s1>>s2; cout<<func(s1,s2)<<endl; return 0; }
时间: 2024-03-18 12:40:01 浏览: 20
你的代码有一些问题,可能会导致输出不正确或者出现运行时错误。正确的最长公共前缀代码可以参考下面的实现:
```cpp
#include <iostream>
#include <string>
using namespace std;
string longestCommonPrefix(string s1, string s2) {
int i = 0;
while (i < s1.length() && i < s2.length() && s1[i] == s2[i]) {
i++;
}
return s1.substr(0, i);
}
int main() {
string s1, s2;
cin >> s1 >> s2;
cout << longestCommonPrefix(s1, s2) << endl;
return 0;
}
```
这里使用了 `substr` 函数来截取字符串的前缀部分,避免了使用指针操作的问题。
相关问题
#include <iostream> #include <string> #include <stack> #include <vector> #include <iomanip> using namespace std; 逐行注释以上代码
这是一段C++的程序代码,使用了几个标准库的头文件。以下是逐行的注释:
```
#include <iostream> // 输入输出流库头文件
#include <string> // 字符串库头文件
#include <stack> // 栈库头文件
#include <vector> // 向量库头文件
#include <iomanip> // 格式控制库头文件
using namespace std; // 命名空间
```
这段程序代码导入了五个标准库的头文件,分别是iostream、string、stack、vector、iomanip,它们分别用于处理输入输出、字符串、栈、向量和格式控制。其中iostream是C++中最常用的输入输出流库,string是用于字符串操作的库,stack是用于栈数据结构的库,vector是用于动态数组的库,iomanip是用于格式化输出的库。
最后一行代码使用了命名空间std,这意味着所有的标准库函数和变量都在std命名空间中。如果不使用using namespace std,则需要在使用标准库函数时加上std::前缀。
#include <iostream> #include <queue> #include <string> using namespace std;对代码进行注释
代码注释如下:
```c++
#include <iostream> // 引入输入输出流库
#include <queue> // 引入队列库
#include <string> // 引入字符串库
using namespace std; // 使用 std 命名空间
// 主函数
int main() {
queue<string> q; // 定义一个字符串队列 q
// 往队列中添加元素
q.push("apple");
q.push("banana");
q.push("orange");
// 输出队列头部元素
cout << q.front() << endl; // 输出:apple
// 弹出队列头部元素
q.pop();
// 输出队列头部元素
cout << q.front() << endl; // 输出:banana
// 输出队列中元素的个数
cout << "The size of the queue is " << q.size() << endl; // 输出:The size of the queue is 2
return 0; // 返回 0 表示程序正常结束
}
```