vc6.03、输入三个字符串,按照由大到小的顺序输出,要求用指针方法处理。
时间: 2023-12-10 10:39:51 浏览: 33
以下是用指针方法处理的示例代码:
```c++
#include <iostream>
#include <cstring>
using namespace std;
void sortStrings(char** strings) {
char* temp;
for (int i = 0; i < 2; i++) {
for (int j = i + 1; j < 3; j++) {
if (strcmp(strings[i], strings[j]) < 0) {
temp = strings[i];
strings[i] = strings[j];
strings[j] = temp;
}
}
}
}
int main() {
char* strings[3];
char buffer[100];
for (int i = 0; i < 3; i++) {
cout << "Enter string " << i + 1 << ": ";
cin.getline(buffer, 100);
strings[i] = new char[strlen(buffer) + 1];
strcpy(strings[i], buffer);
}
sortStrings(strings);
cout << "Sorted strings:" << endl;
for (int i = 0; i < 3; i++) {
cout << strings[i] << endl;
delete[] strings[i];
}
return 0;
}
```
在这个示例中,我们使用了一个字符串指针数组 `char** strings` 来存储输入的三个字符串。然后我们使用 `cin.getline()` 函数从输入流中读取每个字符串,并使用 `new` 运算符为每个字符串分配内存空间。
接着,我们使用 `sortStrings()` 函数对字符串进行排序。这个函数使用两层循环来遍历所有字符串,并使用 `strcmp()` 函数比较它们的大小。如果前面的字符串比后面的字符串小,就交换它们的指针。
最后,我们遍历排序后的字符串指针数组,并依次输出每个字符串。由于我们使用了 `new` 运算符为每个字符串分配了内存空间,所以在程序结束时需要使用 `delete[]` 运算符释放这些内存空间。