【C++的取经之路】(五)文本函数与cin返回值作判断条件

前言

本文围绕C++的文本函数和如何用cin的返回值(True/False)作为判断条件分别展开介绍。参考《C++ Primer Plus》,本篇文章代码均已测试通过。


一、新建头文件和修改源文件

同样的步骤,先按模版新建Day03.h头文件,定义int Day_03(...) {}函数,后在BasicFunc.h文件中导入,再在main.cpp的程序入口函数main()函数中调用该函数。如下:

在这里插入图片描述
在这里插入图片描述

二、分支语句和逻辑运算符

废话不多说,直接上代码:

  • 计算输入的字符数
void countText(int isCountText)
{
	/*计算输入文本中的字符数和空格数*/
	cout << "=======Count Text=======" << endl;

	cout << "Enter the text you want: \n";
	char ch;
	int spaces = 0;
	int total = 0;
	cin.get(ch);
	while (ch != '.')
	{
		if (ch == ' ')
			++spaces;
		++total;
		cin.get(ch);
	};
	cout << spaces << " spaces, " << total;
	cout << " characters total in sentence\n";
}

  • 判断字符类型
void charType(int isCharType)
{
	/*判断字符类型*/
	cout << "=======Char Type=======" << endl;

	char ch;
	int whitespace = 0, digits = 0, chars = 0, punct = 0, others = 0;

	cin.get(ch);
	while (ch != '@')
	{
		if (isalpha(ch))
			chars++;
		else if (isspace(ch))
			whitespace++;
		else if (isdigit(ch))
			digits++;
		else if (ispunct(ch))
			punct++;
		else
			others++;
		cin.get(ch);
	}
	cout << chars << " letters, "
		<< whitespace << " whitespaces, "
		<< digits << " digits, "
		<< punct << " punctations, "
		<< others << " others.\n";
}

  • 条件运算符代替if-else
void condit(int isCondit)
{
	/*条件运算符替代 if-else*/
	cout << "=======Condition code=======" << endl;

	const char x[2][20] = { "Jack ", "at your service\n" };
	const char* y = "Quillstone";

	for (int i = 0; i < 3; i++)
		cout << ((i < 2) ? !i ? x[i] : y : x[1]);
}

  • 字符变量与int的转换
void chooseColor(int isChooseColor)
{
	/*将枚举变量与int变量进行转换*/
	cout << "=======Choose Color=======" << endl;

	enum {red, orange, yellow, green, blue, violet, indigo};
	int code;
	cout << "Enter color code (0 - 6): ";
	cin >> code;
	while (code >= red && code <= indigo)
	{
		switch (code)
		{
			case red: cout << "It's red.\n"; break;
			case orange: cout << "It's orange.\n"; break;
			case yellow: cout << "It's yellow.\n"; break;
			case green: cout << "It's green.\n"; break;
			case blue: cout << "It's blue.\n"; break;
			case violet: cout << "It's violet.\n"; break;
			case indigo: cout << "It's indigo.\n"; break;
		}
		cout << "Enter color code (0 - 6): ";
		cin >> code;
	};
	cout << "【Out】\n";
}

  • 利用cin返回值作为条件
void countFish(int isCountFish)
{
	/*利用cin的返回值作为条件*/
	cout << "=======Count Fish=======" << endl;

	const int Max = 5;
	double fish[Max];
	cout << "Please enter the weights of your fish.\n"
		<< "You may enter up to " << Max << " fish <q to terminate>.\n";
	
	// 如果&&左侧的语句为假,则不会判断右侧的表达式
	/*
	cout << "fish #1: ";
	int i = 0;
	while (i < Max && cin >> fish[i])
	{
		if (++i < Max)
			cout << "fish #" << i + 1 << ": ";
	};
	*/
	// 添加字符纠正cin输入后:
	int i;
	for (i = 0; i < Max; i++)
	{
		cout << "fish #" << i + 1 << ": ";
		while (!(cin >> fish[i]))
		{
			cin.clear();
			while (cin.get() != '\n')
				continue;
			cout << "Please enter a number: ";
		}
	}

	double total = 0.0;
	for (int j = 0; j < i; j++)
		total += fish[j];
	if (i == 0)
		cout << "No fish\n";
	else
		cout << total / i << " = average weight of " << i << "fish\n";
	cout << "Done.\n";

}

  • 文本函数
void editTxtFile(int isEditTxtFile)
{
	/*Cpp的文本函数*/
	cout << "=======Edit TxtFile=======" << endl;

	char automobile[8];
	int year;
	double a_price, b_price;

	ofstream outFile;
	outFile.open("editOutFile.txt");

	// 保存屏幕输出的文本字符串及数据
	cout << "Enter the make and model of automobile: ";
	cin >> automobile;
	cout << "Enter the model year: ";
	cin >> year;
	cout << "Enter the original asking price: ";
	cin >> a_price;
	b_price = 0.913 * a_price;

	// 屏幕上输出信息
	cout << fixed;		// ios文件定义函数
	cout.precision(2);
	cout.setf(ios_base::showpoint);
	cout << "Make and model: " << automobile << endl;
	cout << "Year: " << year << endl;
	cout << "Was asking $" << a_price << endl;
	cout << "Now asking $" << b_price << endl;

	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 $" << b_price << endl;

	outFile.close();

	// 打开已创建的文本文件,计算文件中的数值
	const int SIZE = 60;
	char filename[SIZE];
	ifstream inFile;
	cout << "Enter the name of data file: ";
	cin >> filename;
	inFile.open(filename);
	if (!inFile.is_open())
	{
		cout << "Could not open the file " << filename << endl;
		cout << "Program terminating\n";
		exit(EXIT_FAILURE);
	}
	double value;
	double sum = 0.0;
	int count = 0;

	inFile >> value;
	// not EOF
	while (inFile.good())
	{
		++count;
		sum += value;
		inFile >> 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();
}

Day03.h中的全部代码:

/*Day03:
*	1.学习C++基础语法,包括分支语句和逻辑运算符
*	2.记忆vs c++软件快捷键
Larissa857
2/7/2025
*/

#pragma once
#include "source.h"

using namespace std;

void showmenu_03(void);		// 展示功能菜单
void countText(int isCountText);			// 计算输入文本中的空格数和英文字符数
void charType(int isCharType);				// 判断字符类型
void condit(int isCondit);					// 条件运算符的简洁表达
void chooseColor(int isChooseColor);		// 将枚举变量与int变量进行比较
void countFish(int isCountFish);		// 计算捕获的鱼数量,关键在利用cin的返回值作为条件
void editTxtFile(int isEditTxtFile);	// Cpp的文本函数

int Day_03()
{
	int sign;

	cout << "Hello! Welcome to the C++ world——Day03";
	cout << endl;
	cout << "What can I help you?" << endl;
	showmenu_03();
	cin >> sign;

	switch (sign)
	{
		case 0: cout << "【Done】" << endl; break;
		case 1: countText(sign); break;
		case 2: charType(sign); break;
		case 3: condit(sign); break;
		case 4: chooseColor(sign); break;
		case 5: countFish(sign); break;
		case 6: editTxtFile(sign); break;
		case 7: cout << "Nothing to deal with :)" << endl; break;
	}

	return 3;
}

void showmenu_03(void)
{
	/*展示功能函数菜单*/
	cout << "Please enter 1, 2, 3, 4, 5 or 6:\n"
		"1) countText\t\t\t2) charType\n"
		"3) condit	\t\t4) chooseColor\n"
		"5) countFish\t\t\t6) editTxtFile\n"
		"7) quit\n";
}

void countText(int isCountText)
{
	/*计算输入文本中的字符数和空格数*/
	cout << "=======Count Text=======" << endl;

	cout << "Enter the text you want: \n";
	char ch;
	int spaces = 0;
	int total = 0;
	cin.get(ch);
	while (ch != '.')
	{
		if (ch == ' ')
			++spaces;
		++total;
		cin.get(ch);
	};
	cout << spaces << " spaces, " << total;
	cout << " characters total in sentence\n";
}

void charType(int isCharType)
{
	/*判断字符类型*/
	cout << "=======Char Type=======" << endl;

	char ch;
	int whitespace = 0, digits = 0, chars = 0, punct = 0, others = 0;

	cin.get(ch);
	while (ch != '@')
	{
		if (isalpha(ch))
			chars++;
		else if (isspace(ch))
			whitespace++;
		else if (isdigit(ch))
			digits++;
		else if (ispunct(ch))
			punct++;
		else
			others++;
		cin.get(ch);
	}
	cout << chars << " letters, "
		<< whitespace << " whitespaces, "
		<< digits << " digits, "
		<< punct << " punctations, "
		<< others << " others.\n";
}

void condit(int isCondit)
{
	/*条件运算符替代 if-else*/
	cout << "=======Condition code=======" << endl;

	const char x[2][20] = { "Jack ", "at your service\n" };
	const char* y = "Quillstone";

	for (int i = 0; i < 3; i++)
		cout << ((i < 2) ? !i ? x[i] : y : x[1]);
}

void chooseColor(int isChooseColor)
{
	/*将枚举变量与int变量进行转换*/
	cout << "=======Choose Color=======" << endl;

	enum {red, orange, yellow, green, blue, violet, indigo};
	int code;
	cout << "Enter color code (0 - 6): ";
	cin >> code;
	while (code >= red && code <= indigo)
	{
		switch (code)
		{
			case red: cout << "It's red.\n"; break;
			case orange: cout << "It's orange.\n"; break;
			case yellow: cout << "It's yellow.\n"; break;
			case green: cout << "It's green.\n"; break;
			case blue: cout << "It's blue.\n"; break;
			case violet: cout << "It's violet.\n"; break;
			case indigo: cout << "It's indigo.\n"; break;
		}
		cout << "Enter color code (0 - 6): ";
		cin >> code;
	};
	cout << "【Out】\n";
}

void countFish(int isCountFish)
{
	/*利用cin的返回值作为条件*/
	cout << "=======Count Fish=======" << endl;

	const int Max = 5;
	double fish[Max];
	cout << "Please enter the weights of your fish.\n"
		<< "You may enter up to " << Max << " fish <q to terminate>.\n";
	
	// 如果&&左侧的语句为假,则不会判断右侧的表达式
	/*
	cout << "fish #1: ";
	int i = 0;
	while (i < Max && cin >> fish[i])
	{
		if (++i < Max)
			cout << "fish #" << i + 1 << ": ";
	};
	*/
	// 添加字符纠正cin输入后:
	int i;
	for (i = 0; i < Max; i++)
	{
		cout << "fish #" << i + 1 << ": ";
		while (!(cin >> fish[i]))
		{
			cin.clear();
			while (cin.get() != '\n')
				continue;
			cout << "Please enter a number: ";
		}
	}

	double total = 0.0;
	for (int j = 0; j < i; j++)
		total += fish[j];
	if (i == 0)
		cout << "No fish\n";
	else
		cout << total / i << " = average weight of " << i << "fish\n";
	cout << "Done.\n";

}

void editTxtFile(int isEditTxtFile)
{
	/*Cpp的文本函数*/
	cout << "=======Edit TxtFile=======" << endl;

	char automobile[8];
	int year;
	double a_price, b_price;

	ofstream outFile;
	outFile.open("editOutFile.txt");

	// 保存屏幕输出的文本字符串及数据
	cout << "Enter the make and model of automobile: ";
	cin >> automobile;
	cout << "Enter the model year: ";
	cin >> year;
	cout << "Enter the original asking price: ";
	cin >> a_price;
	b_price = 0.913 * a_price;

	// 屏幕上输出信息
	cout << fixed;		// ios文件定义函数
	cout.precision(2);
	cout.setf(ios_base::showpoint);
	cout << "Make and model: " << automobile << endl;
	cout << "Year: " << year << endl;
	cout << "Was asking $" << a_price << endl;
	cout << "Now asking $" << b_price << endl;

	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 $" << b_price << endl;

	outFile.close();

	// 打开已创建的文本文件,计算文件中的数值
	const int SIZE = 60;
	char filename[SIZE];
	ifstream inFile;
	cout << "Enter the name of data file: ";
	cin >> filename;
	inFile.open(filename);
	if (!inFile.is_open())
	{
		cout << "Could not open the file " << filename << endl;
		cout << "Program terminating\n";
		exit(EXIT_FAILURE);
	}
	double value;
	double sum = 0.0;
	int count = 0;

	inFile >> value;
	// not EOF
	while (inFile.good())
	{
		++count;
		sum += value;
		inFile >> 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();
}

运行一下:

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Larissa857

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值