Learning of C++ programming


foreword

C++ Programming (Fourth Edition) Chapter 5 Using Arrays to Process Batch Data


5.5.6 Application example of character array

Example: There are 3 country names, and it is required to find the first country in alphabetical order. Requires a function call.

#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;
}

operation result

insert image description here

possible problems

The original code uses strcpy instead of strcpy_s, and there will be warnings like
'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
.
I am using visual studio version 2022.

Solution

  1. Find [Project Properties], click [Preprocessor] in [C++], edit [Preprocessor], and add a piece of code in it: _CRT_SECURE_NO_WARNINGS.insert image description here
  2. Rewrite strcpy to strcpy_s.

This kind of warning from Microsoft is mainly because of the functions of the C library. Many functions do not perform parameter detection (including out-of-bounds classes). Microsoft is worried that using these functions will cause memory exceptions, so they rewrite the functions with the same function. The function of the parameter detection, using these new functions will be safer and more convenient.

Guess you like

Origin blog.csdn.net/qq_52992084/article/details/131157868