#include<bits/stdc++.h> using namespace std; void delchar(char *str,char c); int main() { int n=0,repeat; char s[10][1000]={0},c1[10]={0}; cin>>repeat; for(n=0;n<repeat;n++) { getchar(); gets(s[n]); c1[n]=getchar(); } for(n=0;n<repeat;n++) delchar(s[n],c1[n]); return 0; } void delchar(char *str,char c) { char *p,*q; for(p=q=str;*p != '\0';p++) if(*p != c) *q++ = *p; *q = *p; cout<<"result:"<<str<<endl; }
时间: 2024-04-10 08:26:50 浏览: 23
这段代码存在一些问题。首先,`#include<bits/stdc++.h>` 是一个非标准的头文件,不建议使用。正确的做法是包含需要的特定头文件,例如 `<iostream>` 和 `<cstring>`。
其次,`gets` 函数已经在 C++11 中被弃用,并且在 C++14 中已经被移除。建议使用 `std::cin` 或 `std::getline` 来读取输入。
此外,`s` 和 `c1` 数组的大小被固定为 10,这可能导致溢出。建议使用动态内存分配或使用 `std::string` 类型来处理字符串。
最后,在 `delchar` 函数中,将结果打印到 `cout` 是不正确的做法,因为 `str` 是一个指向字符数组的指针,修改它将修改原始的输入字符串。可以考虑返回一个新的字符串来表示删除字符后的结果。
下面是修正后的代码示例:
```cpp
#include <iostream>
#include <cstring>
void delchar(char *str, char c);
int main()
{
int n = 0, repeat;
char **s, *c1;
std::cin >> repeat;
s = new char*[repeat];
c1 = new char[repeat];
for (n = 0; n < repeat; n++)
{
std::cin.ignore(); // 忽略换行符
s[n] = new char[1000];
std::cin.getline(s[n], 1000);
std::cin >> c1[n];
}
for (n = 0; n < repeat; n++)
{
delchar(s[n], c1[n]);
std::cout << "result: " << s[n] << std::endl;
}
// 释放内存
for (n = 0; n < repeat; n++)
delete[] s[n];
delete[] s;
delete[] c1;
return 0;
}
void delchar(char *str, char c)
{
char *p, *q;
for (p = q = str; *p != '\0'; p++)
{
if (*p != c)
*q++ = *p;
}
*q = '\0';
}
```
请注意,上述代码仅仅是为了修复问题,并不保证完全正确或没有其他问题。建议在使用之前进行测试和验证。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![h](https://img-home.csdnimg.cn/images/20210720083646.png)
![h](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)