zl程序教程

您现在的位置是:首页 >  后端

当前栏目

解答私信@被c++折磨头秃的花季美少女 //C++ 利用指针数组输入10个单词,编写函数对10个单词进行排序并输出,要求判断是否有相同的单词,如果有相同的单词在输出时该单词只输出一次。

C++输入输出数组排序 函数 利用 进行
2023-09-14 09:06:59 时间

利用指针数组输入10个单词,编写函数对10个单词进行排序并输出,要求判断是否有相同的单词,如果有相同的单词在输出时该单词只输出一次。

 

注意:此代码在win32控制台运行,在不同的IDE环境下,有部分可能需要变更。
IDE工具:Visual Studio 2010

 

代码块:

#include <iostream>
using namespace std;

void input(char **word, int n);
void output(char **word, int n);
void sort(char **word, int n);

int main()
{
	char *word[10];
	input(word, 10);
	sort(word, 10);
	output(word, 10);
	system("pause");
	return 0;
}

void input(char **word, int n){
	cout<<"Enter "<<n<<" words: ";
	for(int i=0; i<n; i++){
		word[i]=new char[20];
		cin>>word[i];
	}
}
void sort(char **word, int n){
	char **p, **q, *temp;
	for(p=word; p<word+n; p++){
		for(q=p+1; q<word+n; q++){
			if(**p==**q)
				*q="\0";
			else if(**p>**q){
				temp=*p;
				*p=*q;
				*q=temp;
			}
		}
	}
}
void output(char **word, int n){
	int i;
	cout<<"Output: ";
	for(i=0; i<n; i++){
		if(word[i]=="\0")
			continue;
		cout<<word[i]<<" ";
		free(word[i]);
	}
	cout<<endl;
}