C++练习:7.4.2
2、定义string对象数组或二维字符数组,输入10个国家名称,升序排序后输出。
PS:我用的是visual studio 2019,所以不用加一些头文件
string对象数组
#include<iostream>
#include<iomanip>
#include<cmath>
#include<string>
using namespace std;
/******************************************/
/******************************************/
/***********20 软件 程崎*****************/
/******************************************/
/******************************************/
void sort(string x[], int n)
{
//从小到大排序
int i, j;
string t;
for (i = 0; i < n-1; i++)
{
for (j = 0; j < n-i-1; j++)
{
if (x[j]>x[j+1])
{
t = x[j];
x[j] = x[j + 1];
x[j + 1] = t;
}
}
}
}
int main()
{
//2、定义string对象数组或二维字符数组,输入10个国家名称,升序排序后输出。
string a[10];
cout << "请输入十个国家名称" << endl;
for (int i = 0; i < 10; i++)
{
cin >> a[i];
}
sort(a, 10);
cout << "---------------排序后---------------" << endl;
for (int j = 0;j < 10;j++)
{
cout << a[j] << endl;
}
}
二维字符数组
#include<iostream>
#include<iomanip>
#include<cmath>
using namespace std;
/******************************************/
/******************************************/
/***********20 软件 程崎*****************/
/******************************************/
/******************************************/
void changed(char str1[], char str2[])
{
char str3[80];
strcpy(str3, str1);
strcpy(str1, str2);
strcpy(str2, str3);
}
int main()
{
//2、定义string对象数组或二维字符数组,输入10个国家名称,升序排序后输出。
char a[10][80];
cout << "请输入十个国家名称" << endl;
for (int i = 0; i < 10; i++)
{
cin.getline(a[i], 80);
}
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9-i; j++)
{
if (strcmp(a[j], a[j + 1]) > 0)
{
changed(a[j], a[j + 1]);
}
}
}
cout << "------------------------排序后----------------------------" << endl;
for (int j = 0; j < 10; j++)
{
cout << a[j] << endl;
}
return 0;
}
鄙人在编写代码时遇到了strcpy函数不能使用的情况,报错信息为:error C4996: ‘strcpy’: This function or variable may be unsafe。应该是因为微软担心这些函数会造成栈溢出,所以在使用这个函数时会报错(不是所有人都有这个问题,我不知道为啥我会遇到,可能是嫉妒我长得帅吧)
解决方法如下
找到属性
在预处理器中点击那个向下的箭头,出现编辑,点击编辑
然后就出现了这个页面,在里面添加
_CRT_SECURE_NO_WARNINGS
然后一路点确定,这个问题就解决啦
运行结果如图