#include<iostream> #include<cstring> using namespace std; class CSTRING { private: char *p; public: CSTRING() { p = new char[10]; strcpy(p,""); } CSTRING(const char *str) { p = new char[strlen(str) + 1]; strcpy(p, str); } CSTRING(const CSTRING &str) { p = new char[strlen(str.p) + 1]; strcpy(p, str.p); } ~CSTRING() { if (p != NULL) { delete[] p; } } bool operator > (const CSTRING &str) const { return strcmp(p, str.p) > 0; } CSTRING& operator = (const CSTRING &str) { if(this==&str) { return *this; } delete [] p; p=new char[strlen(str.p)+1]; strcpy(p,str.p); return *this; } CSTRING& operator += (const CSTRING &str) { char *temp = new char[strlen(p) + 1]; strcpy(temp, p); char *ans = new char[strlen(p) + strlen(str.p) + 3]; strcat(ans,temp); strcpy(ans,"--"); strcat(ans, str.p); if (p != NULL) { delete[] p; } p = ans; return *this; } friend istream& operator >> (istream &in, CSTRING &str) { char temp[100]; in >> temp; str = CSTRING(temp); return in; } friend ostream& operator << (ostream &out, const CSTRING &str) { out <<str.p; return out; } }; int main() { #ifdef _CRT_SECURE_NO_WARNINGS freopen("./in.txt", "r", stdin); freopen("./out.txt", "w", stdout); #endif int n,i,j; while(cin>>n) { CSTRING *c=new CSTRING[n+2]; for(i=0;i<n;i++) { cin>>c[i]; } for(i=0;i<n-1;i++) for(j=0;j<n-1-i;j++) if(c[j]>c[j+1]) { c[n]=c[j]; c[j]=c[j+1]; c[j+1]=c[n]; } for(i=0;i<n;i++) { c[n+1]+=c[i]; } cout<<c[n+1]<<endl; delete[] c; } return 0; },上述代码,在输入3 aaa bbb ccc时要实现输出--aaa--bbb--ccc应该怎样修改
时间: 2024-01-23 10:04:17 浏览: 245
使用include <iostream>时一定要加using namespace std
在主函数中的最后输出语句,将 `c[n+1]` 改为 `cout << "--" << c[n+1] << "--" << endl;` 即可在输出时添加 "--"。修改后的代码如下:
```cpp
int main() {
#ifdef _CRT_SECURE_NO_WARNINGS
freopen("./in.txt", "r", stdin);
freopen("./out.txt", "w", stdout);
#endif
int n, i, j;
while (cin >> n) {
CSTRING *c = new CSTRING[n + 2];
for (i = 0; i < n; i++) {
cin >> c[i];
}
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - 1 - i; j++) {
if (c[j] > c[j + 1]) {
c[n] = c[j];
c[j] = c[j + 1];
c[j + 1] = c[n];
}
}
}
for (i = 0; i < n; i++) {
c[n + 1] += c[i];
}
cout << "--" << c[n + 1] << "--" << endl;
delete[] c;
}
return 0;
}
```
阅读全文