C++ Primer plus 第六章

6.1 if.cpp

代码

#include <iostream>

using namespace std;

int main()
{
	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";

	return 0;
}

结果

在这里插入图片描述

知识点

1.while与if的嵌套
2.该程序的功能为统计字符串的空格数和总字符数

6.2 ifelse.cpp

代码

#include <iostream>

using namespace std;

int main()
{
	char ch;
	cout << "Type, and I shall repeat.\n";
	cin.get(ch);
	while (ch != '.')
	{
		if (ch == '\n')
		{
			cout << ch;
		}
		else
		{
			cout << ++ch;
		}
		cin.get(ch);

	}
	cout << "\nPlease excuse the slight confusion.\n";

	return 0;
}

结果

在这里插入图片描述

知识点

  1. if…else

6.3 ifelseif.cpp

代码

#include <iostream>

using namespace std;

const int Fave = 27;

int main()
{
	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);

	return 0;
}

结果

在这里插入图片描述

知识点

1.if…else if…else

6.4 or.cpp

代码

#include <iostream>

using namespace std;

int main()
{
	cout << "This program may reformat your hard disk\n"
		"and destroy all your data.\n"
		"Do you wish to continue? <y/n> ";
	char ch;
	cin >> ch;
	if (ch == 'y' || ch == 'Y')
	{
		cout << "You were warned!\a\a\n";
	}
	else if (ch == 'n' || ch == 'N')
	{
		cout << "A wish choice ... bye\n";
	}
	else
	{
		cout << "That was not a y or n! Apparently you "
			"can not follow\ninstructions, so "
			"I will trash your disk anyway.\a\a\a\n";
	}

	return 0;
}

结果

在这里插入图片描述

知识点

1.cout输出字符串时,当字符串过长时,可以通过多个双引号解决
2.or表示或

6.5 and.cpp

代码

#include <iostream>

using namespace std;

const int ArSize = 6;

int main()
{
	float naaq[ArSize];
	cout << "Enter the NAAQs (New Age Awarenss Quotients) "
		<< "of\nyour neighbors. Program terminates "
		<< "when you make\n" << ArSize << " entries "
		<< "or enter a negative value.\n";

	int i = 0;
	float temp;
	cout << "First value: ";
	cin >> temp;

	while (i < ArSize && temp >= 0)
	{
		naaq[i] = temp;
		++i;
		if (i < ArSize)
		{
			cout << "Next value: ";
			cin >> temp;
		}
	}

	if (i == 0)
	{
		cout << "No data -- bye\n";
	}
	else
	{
		cout << "Enter your NAAQ: ";
		float you;
		cin >> you;

		int count = 0;
		for (int j = 0; j < i; j++)
		{
			if (naaq[j] > you)
			{
				++count;
			}
		}
		cout << count;
		cout << " of your neighbors have greater awareness of\n"
			<< "the New Age than you do.\n";
	}

	return 0;
}

结果

在这里插入图片描述

知识点

1.和:&&

6.6 more_and.cpp

代码

#include <iostream>

using namespace std;

const char* qualify[4] =
{
	"10,000-meter race.\n",
	"mud tug-of-war.\n",
	"masters canoe jousting.\n",
	"pie-throwing festival.\n"
};

int main()
{
	int age;
	cout << "Enter your age in years: ";
	cin >> age;
	int index;

	if (age > 17 && age < 35)
		index = 0;
	else if (age >= 35 && age < 50)
		index = 1;
	else if (age >= 50 && age < 65)
		index = 2;
	else
		index = 3;

	cout << "You qualify for the " << qualify[index];
	
	return 0;
}

结果

在这里插入图片描述

知识点

1.&&设置范围

6.7 not.cpp

代码

#include<iostream>
#include<climits>

using namespace std;

bool is_int(double);

int main()
{
	double num;

	cout << "Yo, dude! Enter an integer value: ";
	cin >> num;
	while (!is_int(num))
	{
		cout<< "Out of range -- please try again: ";
		cin >> num;
	}
	int val = int(num);
	cout << "You have entered the integer " << val << "\nBye\n";

	return 0;
}

bool is_int(double x)
{
	if (x <= INT_MAX && x >= INT_MIN)
		return true;
	else
		return false;
}

结果

在这里插入图片描述

知识点

1.非:!

6.8 cctypes.cpp

代码

#include <iostream>
#include <cctype>

using namespace std;

int main()
{
	cout << "Enter text for analysis, and type @"
		" to terminate input.\n";
	char ch;
	int whitespace = 0;
	int digits = 0;
	int chars = 0;
	int punct = 0;
	int others = 0;

	cin.get(ch);
	while (ch != '@')
	{
		if (isalpha(ch))
			chars++;
		else if (isspace(ch))
			whitespace++;
		else if (ispunct(ch))
			punct++;
		else
			others++;
		cin.get(ch);
	}

	cout << chars << " letters, "
		<< whitespace << " whitespace, "
		<< digits << " digits, "
		<< punct << " punctuations, "
		<< others << " others.\n";

	return 0;
}

结果

在这里插入图片描述

知识点

1.cctype包含了一些处理字符函数

6.9 condit.cpp

代码

#include <iostream>

using namespace std;

int main()
{
	int a, b;
	cout << "Enter two integers: ";
	cin >> a >> b;
	cout << "The larger of " << a << " and " << b;
	int c = a > b ? a : b;//c = a if a > b,else c = b
	cout << " is " << c << endl;
	
	return 0;
}

结果

在这里插入图片描述

知识点

1.3个操作数的运算符

6.10switch.cpp

代码

#include <iostream>

using namespace std;

void showmenu();
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";
	cin.get();
	cin.get();

	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";

}

结果

在这里插入图片描述

知识点

  1. switch

6.11 enum.cpp

代码

#include <iostream>

using namespace std;

enum{red, orange, yellow, green, blue, violet, indigo};

int main()
{
	cout << "Enter color code (0-6): ";
	int code;
	cin >> code;

	while (code >= red && code <=indigo)
	{
		switch (code)
		{
		case red: cout << "Her lips were red.\n"; break;
		case orange: cout << "Her lips were orange.\n"; break;
		case yellow: cout << "Her lips were yellow.\n"; break;
		case green: cout << "Her lips were green.\n"; break;
		case blue: cout << "Her lips were blue.\n"; break;
		case violet: cout << "Her lips were violet.\n"; break;
		case indigo: cout << "Her lips were indigo.\n"; break;
		}
		cout << "Enter color code (0-6): ";
		cin >> code;
	}
	cout << "Bye\n";

	return 0;
}

结果

在这里插入图片描述

知识点

1.enum

6.12 jump.cpp

代码

#include <iostream>

using namespace std;

const int ArSize = 80;

int main()
{
	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];
		if (line[i] == '.')
			break;
		if (line[i] != ' ')
			continue;
		spaces++;
	}
	cout << "\n" << spaces << " spaces\n";
	cout << "Done.\n";

	return 0;
}

结果

在这里插入图片描述

知识点

1.break
2.continue

6.13 cinfish.cpp

代码

#include <iostream>

using namespace std;

const int Max = 5;

int main()
{
	double fish[Max];

	cout << "Please enter the weights of your fish.\n";
	cout << "You may enter up to " << Max
		<< " fish <q to terminate>.\n";
	cout << "fish #1: ";

	int i = 0;
	//cin >> fish[i],当cin在while等测试语句中时,被转为bool类型
	//如果输入成功,则值为true,否则为false
	while (i < Max && cin >> fish[i])
	{
		if (++i < Max)//先加后比较
			cout << "fish #" << i + 1 << ": ";
	}

	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";

	return 0;
}

结果

在这里插入图片描述

知识点

  1. cin >> fish[i],当cin在while等测试语句中时,被转为bool类型,如果输入成功,则值为true,否则为false。

6.14 cingolf.cpp

代码

#include <iostream>

using namespace std;

const int Max = 5;

int main()
{
	int golf[Max];
	cout << "Please enter your golf scores.\n";
	cout << "You must enter " << Max << " rounds.\n";
	
	//输入异常处理,cin >> golf[i]为false表示输入错误
	//此时!(cin >> golf[i])为true,进入内循环
	//cin.clear();重置输入
	int i;
	for ( i = 0; i < Max; i++)
	{
		cout << "round #" << i + 1 << ": ";
		while (!(cin>>golf[i]))
		{
			cin.clear();
			while (cin.get() != '\n')
				continue;
			cout << "Please enter a number: ";
		}
	}

	double	total = 0.0;
	for (i = 0; i < Max; i++)
		total += golf[i];

	cout << total / Max << " = average score "
		<< Max << " rounds\n";

	return 0;
}

结果

在这里插入图片描述

知识点

1.cin.clear();

6.15 outfile.cpp

代码

#include <iostream>
#include <fstream>//step1:包含头文件fstream

using namespace std;

int main()
{
	char automobile[50];
	int year;
	double a_price;
	double d_price;

	ofstream outFile;//step2:创建一个fstream对象
	outFile.open("carinfo.txt");//step3:将该fstream对象同一个文件关联起来

	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;

	//使用cout显示
	cout << fixed;
	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 $" << d_price << endl;

	//step4:使用outfile显示
	outFile << fixed;
	outFile.precision(2);
	outFile.setf(ios_base::showpoint);
	cout << "Make and model: " << automobile << endl;
	cout << "Year: " << year << endl;
	cout << "Was asking $" << a_price << endl;
	cout << "Now asking $" << d_price << endl;

	outFile.close();//step5:结束outFile

	return 0;
}


结果

在这里插入图片描述

知识点

1.使用文件输出步骤
step1:包含头文件fstream
step2:创建一个fstream对象
step3:将该fstream对象同一个文件关联起来
step4:使用outfile
step5:结束outFile

6.16 sumafile.cpp

代码

#include <iostream>
#include <fstream>
#include <cstdlib>

using namespace std;

const int SIZE = 60;

int main()
{
	char filename[SIZE];
	ifstream inFile;

	cout << "Enter name of data file: ";
	cin.getline(filename, SIZE);
	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;
	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();//关闭

	return 0;
}

结果

在这里插入图片描述
暂时不知道怎么文件放在什么地方可以读到,先放着。

知识点

1.ifstream inFile用法

总结

继续干

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值