C++程序设计的学习


前言

C++程序设计(第四版)第5章 利用数组处理批量数据


5.5.6 字符数组应用举例

例:有3个国家名,要求找出按字母顺序排在最前面的国家。要求用函数调用。

#include <iostream>
#include <string>

using namespace std;

int main() {
    
    
	void smallest_string(char str[][30], int i);
	int i;
	char country_name[3][30];
	for (i = 0; i < 3; i++)
		cin >> country_name[i];
	smallest_string(country_name, 3);
	return 3;
}

void smallest_string(char str[][30], int n) {
    
    
	int i;
	char string[30];
	strcpy_s(string, str[0]);
	for (i = 0; i < n; i++)
		if (strcmp(str[i], string) < 0)
			strcpy_s(string, str[i]);
			cout << endl << "The smallest string is:" << string << endl;
}

运行结果

在这里插入图片描述

可能会出现的问题

原来代码使用的是strcpy而不是strcpy_s,会出现
‘strcpy’: This function or variable may be unsafe. Consider using strcpy_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
这样的警告。
我使用的是visual studio 2022版。

解决办法

  1. 找到【项目属性】,点击【C++】里的【预处理器】,对【预处理器】进行编辑,在里面加入一段代码:_CRT_SECURE_NO_WARNINGS。在这里插入图片描述
  2. 将strcpy改写为strcpy_s。

这种微软的警告,主要因为那些C库的函数,很多函数内部是不进行参数检测的(包括越界类的),微软担心使用这些会造成内存异常,所以就改写了同样功能的函数,改写了的函数进行了参数的检测,使用这些新的函数会更安全和便捷。

猜你喜欢

转载自blog.csdn.net/qq_52992084/article/details/131157868
今日推荐