小言_互联网的博客

【C++100问】一篇文章(16个小例子)带你入门C++的编程世界(基础篇)

425人阅读  评论(0)

📢 声明:

1)本文仅供学术交流,非商用。
2)博主才疏学浅,文中如有不当之处,请各位指出,共同进步,谢谢。
3)此属于第一版本,若有错误,还需继续修正与增删。还望大家多多指点。
4)大家都共享一点点,一起为祖国科研的推进添砖加瓦。

👉 学习路线

〇、✏ 前言

为了更好地记录学过的C++知识,作者在过去的两个月里,将每个知识点对应的小例子总结下来,分享给大家 💖,希望大家喜欢 😁。

下面开始正文,全程英文注释:

⌛ 加载中 ▶▶▶ ⏳ ...

一、🚀 你好,世界

牙牙学语的开始。

#include <iostream>
int main()
{
	using namespace std;
	
	cout << "Hello,World" << endl;

	system("pause");
	return 0;
}

二、🍄 数据类型

int、short、long、long long、char、float、double、long double 的位数,最大值,最小值。

#include <iostream>
#include <climits>
int main()
{
	using namespace std;
	
	int n_int = INT_MAX;			// initialize n_int to max int value
	short n_short = SHRT_MAX;		// symbols defined in climits file
	long n_long = LONG_MAX;
	long long n_llong = LLONG_MAX;
	char n_char = CHAR_MAX;
	float n_float = FLT_MAX;
	double n_double = DBL_MAX;
	long double n_ldouble = LDBL_MAX;

	// sizeof operator yields size of type or of variable
	cout << "Sizeof:" << endl;
	cout << "int is " << sizeof (int) << " bytes." << endl;
	cout << "short is " << sizeof n_short << " bytes." << endl;
	cout << "long is " << sizeof n_long << " bytes." << endl;
	cout << "long long is " << sizeof n_llong << " bytes." << endl;
	cout << "char is " << sizeof n_char << " bytes." << endl;
	cout << "float is " << sizeof n_float << " bytes." << endl;
	cout << "double is " << sizeof n_double << " bytes." << endl;
	cout << "long double is " << sizeof n_ldouble << " bytes." << endl;
	cout << endl;

	cout << "Maximum values:" << endl;
	cout << "int: " << n_int << endl;
	cout << "short: " << n_short << endl;
	cout << "long: " << n_long << endl;
	cout << "long long: " << n_llong << endl;
	cout << "char is " << n_char << endl;
	cout << "float is " << n_float << endl;
	cout << "double is " << n_double << endl;
	cout << "long double is " << n_ldouble << endl;
	cout << endl;

	cout << "Minimum values:" << endl;
	cout << "int: " << INT_MIN << endl;
	cout << "short: " << SHRT_MIN << endl;
	cout << "long: " << LONG_MIN << endl;
	cout << "long long: " << LLONG_MIN << endl;
	cout << "char is " << CHAR_MIN << endl;
	cout << "float is " << FLT_MIN << endl;
	cout << "double is " << DBL_MIN << endl;
	cout << "long double is " << LDBL_MIN << endl;
	cout << endl;

	cout << "Bits per byte = " << CHAR_BIT << endl;

	system("pause");
	return 0;
}

三、🍅 算术运算符

加法、减法、乘法、除法、求模。

#include <iostream>
int main()
{
	using namespace std;
	
	int hats, heads;
	cout << "Enter a number: ";
	cin >> hats;
	cout << "Enter another number: ";
	cin >> heads;

	cout << "hats = " << hats << "; heads = " << heads << endl;
	cout << "hats + heads = " << hats + heads << endl;
	cout << "hats - heads = " << hats - heads << endl;
	cout << "hats * heads = " << hats * heads << endl;
	cout << "hats / heads = " << hats / heads << endl;
	cout << "hats % heads = " << hats % heads << endl;

	system("pause");
	return 0;
}

四、🍆 复合类型

4.1、🍉 一维数组、字符串、string
#include <iostream>
#include <cstring>
#include <string>		// make string class available
const int Size = 15;
int main()
{
	using namespace std;

	int yams[3];		// creates array with three elements
	yams[0] = 7;		// assign value to first element
	yams[1] = 8;
	yams[2] = 6;

	cout << "Total yams = ";
	cout << yams[0] + yams[1] + yams[2] << "." << endl;
	cout << "The second yams = ";
	cout << yams[1] << ".";
	cout << "\nSize of yams array = " << sizeof yams;
	cout << " bytes.\n";

	cout << endl;
	cout << "********************************分割线********************************" << endl;
	cout << endl;

	char name[Size] = "C++owboy";		// initialized array

	cout << "Well, " << name << ", your name ";
	cout << "is stored in an array of " << sizeof(name) << " bytes.\n";
	cout << "Your initial is " << name[0] << ".\n";
	name[3] = '\0';						// set to null character
	cout << "Here are the first 3 "
		"characters of my name: ";
	cout << name << "." << endl;

	cout << endl;
	cout << "********************************分割线********************************" << endl;
	cout << endl;

	string s1 = "penguin";
	string s2, s3;
	s2 = "buzzard";

	cout << "You can assign two string object: "
		"s1 is " << s1 << ", "
		"s2 is " << s2 << endl;
	s3 = s1 + s2;
	cout << "You can concatenate strings: s3 = s1 + s2";
	cout << " = " << s3;
	cout << "\nSize of s3 = " << sizeof s3 << " bytes.\n" << endl;

	system("pause");
	return 0;
}

4.2、🍊 结构、共用体、枚举
#include <iostream>
struct inflatable				// structure declaration
{
	char name[20];
	float volume;
	double price;
};
union one4all{
	int int_val;
	long long_val;
	double double_val;
};
enum spectrum{
	red, orange, yellow, green
};
int main()
{
	using namespace std;

	inflatable guests[2] =		// initializing an array of structs
	{
		{ "Bambi", 0.5, 21.99 },// first structure in array
		{ "Godzilla", 2000, 565.99 }	// next structure in array
	};
	cout << "The guests " << guests[0].name << " and " << guests[1].name
		<< "\nhave a combined volume of "
		<< guests[0].volume + guests[1].volume << " cubic feet.\n";

	inflatable guest =
	{
		"Glorious Gloria",		// name value
		1.88,					// volume value
		29.99					// price value
	};	// guest is a structure variable of type inflatable
// It's initialized to the indicated values
	inflatable pal =
	{
		"Audacious Arthur",
		3.12,
		32.99
	};	// pal is a second variable of type inflatable
// NOTE: some implementations require using static inflatable guest
	cout << "Expand your guest list with " << guest.name;
	cout << " and " << pal.name << "!\n";
	cout << "You can have both for $";
	cout << guest.price + pal.price << "!\n";

	inflatable choice;
	choice = guest; 		// assign one structure to another
	cout << "The choice: " << choice.name << " for $";
	cout << choice.price << endl;

	cout << endl;
	cout << "********************************分割线********************************" << endl;
	cout << endl;

	one4all pail;
	pail.int_val = 15;
	cout << "The int_val of pail is " << pail.int_val << endl;
	cout << "The double_val of pail is " << sizeof(pail.double_val) << " bytes.\n";

	cout << endl;
	cout << "********************************分割线********************************" << endl;
	cout << endl;

	spectrum band;
	band = green;
	cout << "The band green is " << band << endl;
	int color = orange;
	color = 1 + red;
	band = spectrum(color);
	cout << "The color of 'color = 1 + red' is " << band << endl;

	system("pause");
	return 0;
}

4.3、🍕 二维数组、字符串、string
#include <iostream>
#include <string>
#include <array>
const int Cities = 5;
const int Years = 4;
int main()
{
	using namespace std;

	const string cities[Cities] =   // array of pointers
	{                               // to 5 strings
		"Gribble City",
		"Gribbletown",
		"New Gribble",
		"San Gribble",
		"Gribble Vista"
	};
	array<array<int, Cities>, Years> maxtemps =
	/* int maxtemps[Years][Cities] =   // 2-D array */
	{
		96, 100, 87, 101, 105,   // values for maxtemps[0]
		96, 98, 91, 107, 104,   // values for maxtemps[1]
		97, 101, 93, 108, 107, // values for maxtemps[2]
		98, 103, 95, 109, 108   // values for maxtemps[3]
	};
	cout << "Maximum temperatures for 2008 - 2011\n\n";
	for (int city = 0; city < Cities; ++city)
	{
		cout << cities[city] << ":\t";
		for (int year = 0; year < Years; ++year)
			cout << maxtemps[year][city] << "\t";
		cout << endl;
	}

	system("pause");
	return 0;
}

五、🍇 指针

#include <iostream>
#include <cstring>
struct inflatable						// structure definition
{
	char name[20];
	float volume;
	double price;
};
int main()
{
	using namespace std;

	double * p3 = new double[3];		// space for 3 doubles
	p3[0] = 0.2;						// treat p3 like an array name
	p3[1] = 0.5;
	p3[2] = 0.8;
	cout << "p3[1] is " << p3[1] << ".\n";
	p3 = p3 + 1;						// increment the pointer
	cout << "Now p3[1] is " << p3[1] << ".\n";
	p3 = p3 - 1;						// point back to beginning
	delete[] p3;						// free the memory

	cout << endl;
	cout << "********************************分割线********************************" << endl;
	cout << endl;

	char animal[20] = "bear";			// animal holds bear
	char * ps;							// uninitialized
	cout << animal << " and ";			// display bear
	ps = animal;						// set ps to point to string
	cout << ps << "!\n";				// ok, same as using animal
	cout << "Before using strcpy():\n";
	cout << animal << " at " << (int *)animal << endl;
	cout << ps << " at " << (int *)ps << endl;
	ps = new char[strlen(animal) + 1];	// get new storage
	strcpy(ps, animal);					// copy string to new storage
	cout << "After using strcpy():\n";
	cout << animal << " at " << (int *)animal << endl;
	cout << ps << " at " << (int *)ps << endl;
	delete[] ps;

	cout << endl;
	cout << "********************************分割线********************************" << endl;
	cout << endl;

	inflatable * psa = new inflatable;	// allot memory for structure
	cout << "Enter name of inflatable item: ";
	cin.get(psa->name, 20);				// method 1 for member access
	cout << "Enter volume in cubic feet: ";
	cin >> (*psa).volume;				// method 2 for member access
	cout << "Enter price: $";
	cin >> psa->price;
	cout << "Name: " << (*psa).name << endl;				// method 2
	cout << "Volume: " << psa->volume << " cubic feet\n";	// method 1
	cout << "Price: $" << psa->price << endl;				// method 1
	delete psa;							// free memory used by structure

	system("pause");
	return 0;
}

六、🍈 模板类

vectorarray

#include <iostream>
#include <vector>   // STL C++98
#include <array>    // C++0x
int main()
{
	using namespace std;
	
	// C, original C++
	double a1[4] = { 1.2, 2.4, 3.6, 4.8 };
	// C++98 STL
	vector<double> a2(4);	// create vector with 4 elements
	// no simple way to initialize in C98
	a2[0] = 1.0 / 3.0;
	a2[1] = 1.0 / 5.0;
	a2[2] = 1.0 / 7.0;
	a2[3] = 1.0 / 9.0;
	// C++0x -- create and initialize array object
	array<double, 4> a3 = { 3.14, 2.72, 1.62, 1.41 };
	array<double, 4> a4;
	a4 = a3;				// valid for array objects of same size
	// use array notation
	cout << "a1[2]: " << a1[2] << " at " << &a1[2] << endl;
	cout << "a2[2]: " << a2[2] << " at " << &a2[2] << endl;
	cout << "a3[2]: " << a3[2] << " at " << &a3[2] << endl;
	cout << "a4[2]: " << a4[2] << " at " << &a4[2] << endl;
	// misdeed
	a1[-2] = 20.2;
	cout << "a1[-2]: " << a1[-2] << " at " << &a1[-2] << endl;
	cout << "a3[2]: " << a3[2] << " at " << &a3[2] << endl;
	cout << "a4[2]: " << a4[2] << " at " << &a4[2] << endl;

	system("pause");
	return 0;
}

七、🍌 循环

7.1、🍒 for循环
#include <iostream>
const int ArSize = 15;      // example of external declaration
int main()
{
	using namespace std;
	
	int i;  // create a counter
	// initialize; test ; update
	cout << "Counting by positive(++)" << ".\n";
	for (i = 0; i < 5; i++)
		cout << "C++ knows loops.\n";
	cout << "Counting by negative(--)" << ".\n";
	for (i = 5; i > 0; i--)
		cout << "C++ knows loops.\n";
	int by = 3;
	cout << "Counting by " << by << "s:\n";
	for (i = 5; i > 0; i-=by)
		cout << "C++ knows loops.\n";
	cout << "C++ knows when to stop.\n";

	cout << endl;
	cout << "********************************分割线********************************" << endl;
	cout << endl;

	long long factorials[ArSize];
	factorials[1] = factorials[0] = 1LL;
	for (int i = 2; i < ArSize; i++)
		factorials[i] = i * factorials[i - 1];
	for (int i = 0; i < ArSize; i++)
		cout << i << "! = " << factorials[i] << endl;

	cout << endl;
	cout << "********************************分割线********************************" << endl;
	cout << endl;

	int a = 20;
	int b = 20;
	cout << "a   = " << a << ":   b = " << b << "\n";
	cout << "a++ = " << a++ << ": ++b = " << ++b << "\n";
	cout << "a   = " << a << ":   b = " << b << "\n";

	system("pause");
	return 0;
}

7.2、🍓 while循环
#include <iostream>
#include <ctime> // describes clock() function, clock_t type
const int ArSize = 20;
int main()
{
	using namespace std;
	
	cout << "Count the delay time, in seconds.";
	cout << "starting\a\n";
	clock_t start = clock();

	char name[ArSize] = "Fred";
	cout << "Your first name, please is " << name << endl;
	cout << "Here is your verticalized and ASCIIized name:\n";
	int i = 0;                  // start at beginning of string
	while (name[i] != '\0')     // process to end of string
	{
		cout << name[i] << ": " << int(name[i]) << endl;
		i++;                    // don't forget this step
	}
	cout << "Loop done \a\n";

	clock_t end = clock();
	double endtime = (double)(end - start) / CLOCKS_PER_SEC;
	cout << "Total time is: " << endtime << "s" << endl;

	system("pause");
	return 0;
}

7.3、🍔 do while循环
#include <iostream>
int main()
{
	using namespace std;
	
	int n;
	cout << "Enter numbers in the range 1-10 to find ";
	cout << "my favorite number\n";
	do
	{
		cin >> n;       // execute body
	} while (n != 7);   // then test
	cout << "Yes, 7 is my favorite.\n";

	system("pause");
	return 0;
}

八、🍍 分支

8.1、🍖 if else语句
#include <iostream>
const int Fave = 27;
int main()
{
	using namespace std;
	
	int n;
	cout << "Enter a number in the range 1-100 to find ";
	cout << "my favorite number: ";
	do
	{
		cin >> n;
		if (n < Fave)
			cout << "Too low -- guess again: ";
		else if (n > Fave)
			cout << "Too high -- guess again: ";
		else
			cout << Fave << " is right!\n";
	} while (n != Fave);

	system("pause");
	return 0;
}

8.2、🍘 switch语句
#include <iostream>
using namespace std;
void showmenu();   // function prototypes
void report();
void comfort();
int main()
{
	showmenu();
	int choice;
	cin >> choice;
	while (choice != 5)
	{
		switch (choice)
		{
		case 1:   cout << "\a\n";
			break;
		case 2:   report();
			break;
		case 3:   cout << "The boss was in all day.\n";
			break;
		case 4:   comfort();
			break;
		default:   cout << "That's not a choice.\n";
		}
		showmenu();
		cin >> choice;
	}
	cout << "Bye!\n";

	system("pause");
	return 0;
}

void showmenu()
{
	cout << "Please enter 1, 2, 3, 4, or 5:\n"
		"1) alarm           2) report\n"
		"3) alibi           4) comfort\n"
		"5) quit\n";
}
void report()
{
	cout << "It's been an excellent week for business.\n"
		"Sales are up 120%. Expenses are down 35%.\n";
}
void comfort()
{
	cout << "Your employees think you are the finest CEO\n"
		"in the industry. The board of directors think\n"
		"you are the finest CEO in the industry.\n";
}

8.3、🍚 continue / break语句
#include <iostream>
const int ArSize = 80;
int main()
{
	using namespace std;
	
	char line[ArSize];
	int spaces = 0;
	cout << "Enter a line of text:\n";
	cin.get(line, ArSize);
	cout << "Complete line:\n" << line << endl;
	cout << "Line through first period:\n";
	for (int i = 0; line[i] != '\0'; i++)
	{
		cout << line[i];    // display character
		if (line[i] == '.') // quit if it's a period
			break;
		if (line[i] != ' ') // skip rest of loop
			continue;
		spaces++;
	}
	cout << "\n" << spaces << " spaces\n";
	cout << "Done.\n";

	system("pause");
	return 0;
}

九、🍎 简单文件处理

9.1、🍜 文本写入
#include <iostream>
#include <fstream>                  // for file I/O

int main()
{
	using namespace std;

	char automobile[50];
	int year;
	double a_price;
	double d_price;

	ofstream outFile;               // create object for output
	outFile.open("carinfo.txt");    // associate with a file

	cout << "Enter the make and model of automobile: ";
	cin.getline(automobile, 50);
	cout << "Enter the model year: ";
	cin >> year;
	cout << "Enter the original asking price: ";
	cin >> a_price;
	d_price = 0.913 * a_price;

	// display information on file with outFile
	// using outFile instead of cout
	outFile << fixed;
	outFile.precision(2);
	outFile.setf(ios_base::showpoint);
	outFile << "Make and model: " << automobile << endl;
	outFile << "Year: " << year << endl;
	outFile << "Was asking $" << a_price << endl;
	outFile << "Now asking $" << d_price << endl;

	outFile.close();                // done with file

	system("pause");
	return 0;
}



9.2、🍞 文本读出
#include <iostream>
#include <fstream>          // file I/O support
#include <cstdlib>          // support for exit()
const int SIZE = 60;
int main()
{
	using namespace std;
	
	char filename[SIZE];
	ifstream inFile;        // object for handling file input
	cout << "Enter name of data file: ";
	cin.getline(filename, SIZE);
	inFile.open(filename);  // associate inFile with a file
	if (!inFile.is_open())  // failed to open file
	{
		cout << "Could not open the file " << filename << endl;
		cout << "Program terminating.\n";
		// cin.get();    	// keep window open
		exit(EXIT_FAILURE);
	}
	double value;
	double sum = 0.0;
	int count = 0;          // number of items read
	inFile >> value;        // get first value
	while (inFile.good())   // while input good and not at EOF
	{
		++count;            // one more item read
		sum += value;       // calculate running total
		inFile >> value;    // get next value
	}
	if (inFile.eof())
		cout << "End of file reached.\n";
	else if (inFile.fail())
		cout << "Input terminated by data mismatch.\n";
	else
		cout << "Input terminated for unknown reason.\n";
	if (count == 0)
		cout << "No data processed.\n";
	else
	{
		cout << "Items read: " << count << endl;
		cout << "Sum: " << sum << endl;
		cout << "Average: " << sum / count << endl;
	}
	inFile.close();         // finished with the file

	system("pause");
	return 0;
}


如果想要更多的资源,欢迎关注 @我是管小亮,文字强迫症MAX~

回复【福利】即可获取我为你准备的大礼,包括C++,编程四大件,NLP,深度学习等等的资料。

想看更多文(段)章(子),欢迎关注微信公众号「程序员管小亮」~

参考文章

  • 《C++ Primer Plus》第六版

转载:https://blog.csdn.net/TeFuirnever/article/details/103604137
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场