第6章 分支语句和逻辑运算符

//if.cpp--using the if statement
#include<iostream>
int main()
{
    using namespace std;
    char ch;
    int spaces = 0;
    int total = 0;
    cin.get(ch);
    while (ch != '.')
    {
        if (ch == ' ')//空字符的在引号中间 加一个空格
            ++spaces;     //当ch为空字符时 才执行++spaces
        ++total;//total 位于If外面 所以每轮都执行
        cin.get(ch);
    }
    cout << spaces << "spaces," << total;
    cout << "characters total in sentence\n";
    //cin.get();
    //cin.get();
    return 0;
}

if else 语句

//ifelse.cpp--using the if else statement
#include<iostream>
int main()
{
    using namespace std;
    char ch;

    cout << "Type,and i shall repeat.\n";
    cin.get(ch);
    while (ch != '.')
    {
        if (ch == '\n')
            cout << ch;
        else
            cout << ++ch;
        //cout<<ch+1;会出现输出的是数字
        cin.get(ch);
    }

    cout << "\nPlesase excuse the slight confusion.\n";
    //cin.get();
    //cin.get();
    return 0;

}


格式化if else 语句

//ifelse.cpp--using the if else statement
#include<iostream>
int main()
{
    using namespace std;
    char ch;

    cout << "Type,and i shall repeat.\n";
    cin.get(ch);
  
    if (ch == 'a')
    {
        ++ch;
        cout << ch;
    }
    else
    {
       // cout << ++ch;
        cout<<ch+1;//会出现输出的是数字
        cin.get(ch);
    }

    cout << "\nPlesase excuse the slight confusion.\n";
    //cin.get();
    //cin.get();
    return 0;

}


if else if else结构

//ifelseif.cpp---using if else 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);
    //cin.get();
    //cin.get();

    int myNumer=0;
    if (3 == myNumer)
        cout << "i love c++";
    else if ( myNumer==2)//此处发出警告 (2=myNumer)不对 表达式必须是可修改的左值
        //语法不会报错可能程序会出错
        cout << "ok";
    else
        cout << "yes";
        
    return 0;
}

逻辑运算符or||

//or.cpp--using the logical OR operator
#include<iostream>
int main()
{
	using namespace std;
	cout << "This program may reformat your hard disk\n"//重新格式化硬盘
		"and destroy all your data.\n"//销毁
		"Do you wish to contiue?<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 wise choice...bye\n";
	else
		cout << "That wasn't a y or n!Apparently you"
		"can't follow \n instructions,so"//指示
		"I'll trash your disk anyway.\a\a\a\n";
	//cin.get();
	//cin.get();
	return 0;
}

逻辑AND运算符&&

//add.cpp --using the logical AND operator
#include<iostream>
const int ArSize = 6;
int main()
{
	using namespace std;
	float naaq[ArSize];
	cout << "Enter the NAAQs(New Age Awareness Quotients)"
		<< "of\n your 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)//2 quitting criteria
	{
		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";

	}
	//cin.get();
	//cin.get();
	return 0;

}

用&&来设置取值范围

//more_and.cpp--using the logical AND operator
#include<iostream>
const char* qualify[4] =
{
	"10,000-meter race.\n",
	"mud tug-of-war.\n",
	"masters canoe jousting.\n",
	"pie-throwing festival.\n"
};//都是体育运动
int main()
{
	using namespace std;
	int age;
	cout << "Enter your age in years:";
	cin >> age;
	int index;

	if (age > 17 && age < 35)
	//if(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];
	//cin.get();
	//cin.get();
	return 0;
}
//not.cpp--using the not operator
#include<iostream>
#include<climits>//NT_MAX和INT_MIN
bool is_int(double);
int main()
{ 
	using namespace std;
	double num;

	cout << "Yo ,dude!Enter an integer value:";//伙计dude
	cin >> num;
	while (!is_int(num))//continue while num is not int-able
	{
		cout << "Out of range--please try again:";
		cin >> num;
	}
	int val = int(num);//type cast
	cout << "You've entered the integer" << val << "\n Bye \n";
	//cin.get();
	//cin.get();


	int age;
	int weight;
	int donation;
	cin >> age;
	cin >> weight;
	cin>> donation;
	if (age > 30 && age < 45 || weight>300)//&&的优先级高于or
		cout << "fat";
	else if ((age > 50 || weight > 300) && donation > 1000)//先进行OR 则需要扩起来
		cout << "ok";
	else
		cout << "no";

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

字符函数库cctype

//cctypes.cpp--using the ctype.h library
#include<iostream>
#include<cctype>//cctype软件包
int main()
{
	using namespace std;
	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 (isdigit(ch))//数字
			digits++;
		else if (ispunct(ch))//punctuation标点符号
			punct++;
		else
			others++;
		cin.get(ch);
	}
	cout << chars << "letters,"
		<< whitespace << "whitesapce,"
		<< digits << "digits,"
		<< punct << "punctuations,"
		<< others << "other.\n";
	//cin.get();
	//cin.get();
	return 0;

}

?运算符

//condit.cpp--using the conditional operator
#include<iostream>
int main()
{
	using namespace std;
	int a, b;
	cout << "Enter two intergers:";
	cin >> a >> b;
	cout << "The large of " << a << "and" << b;
	int c = a > b ? a : b;//if (a>b) c=a ;else c=b;
	//expression1 ?expression2:expression3 
	//当expression1为ture 表达式的值为expression2 否则为expression3
	cout << "is" << c << endl;
	//cin.get();
	//cin.get();
	return 0;

}
//switch.cpp--using the switch statement
#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 bussiness.\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";
}

switch星期几

#include<iostream>

using namespace std;

int main()
{
	int i;
	cout << "请输入今天是星期几:";
	cin >> i;

	switch (i)
	{
	case1:
		cout << "switch:今天是星期一" << endl;
		break;//遇到break 就停下来 不会贯穿 
	case2:
		cout << "switch:今天是星期二" << endl;
		break;//case不用写大括号
	case3:
		cout << "switch:今天是星期三" << endl;
		break;
	case4:
		cout << "switch:今天是星期四" << endl;
		break;
	case5:
		cout << "switch:今天是星期五" << endl;
		break;
	case6:
		cout << "switch:今天是星期六" << endl;
		break;
	case7:
		cout << "switch:今天是星期天" << endl;
		break;
	default:
		cout << "switch:错误的输入" << endl;
		break;
	}


	/*
	if (i == 1)//if后面可以i可以为小数 可以写i<3小于符号
		cout << "今天是星期一" << endl;
	else if (i == 2)
		cout << "今天是星期二" << endl;
	else if (i == 3)
		cout << "今天是星期三" << endl;
	else if (i == 4)
		cout << "今天是星期四" << endl;
	else if (i == 5)
		cout << "今天是星期五" << endl;
	else if (i == 6)
		cout << "今天是星期六" << endl;
	else if (i == 7)
		cout << "今天是星期天" << endl;
	else
		cout<<"错误的输入"<<endl;
		*/
	return 0;
}
//switch.cpp--using the switch statement
#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();//case后面只能是整数 表示chioce==2 不能为小数(注意与If的区别)
			    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();


/*
int main()
{
char ch;

int aCnt = 0, eCnt = 0, iCnt = 0, oCnt = 0,uCnt=0;
while (cin >> ch)
{
	switch (ch)
	{
	case 'a':
		++aCnt;
		break;
	case'e':
		++eCnt;
		break;
	case'i':
		++iCnt;
		break;
	case'o':
		++oCnt;
		break;
	case'u':
		++uCnt;
		break;

	}
}
cout << "Number of vowel a:\t" << aCnt << '\n';
cout << "Number of vowel e:\t" << eCnt << '\n';
cout << "Number of vowel i:\t" << iCnt << '\n';
cout << "Number of vowel o:\t" << oCnt << '\n';
cout << "Number of vowel u:\t" << uCnt << '\n';

	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 bussiness.\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";
}
*/

if else 和switch区别

  • if else :真/假值 ;关系式; 逻辑表达式 ;浮点值
  • switch:整数值、字符、字符串;多整数值判断;多字符串判断

break和continue语句

//jump.cpp--using continue and 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;//当有两个for循环时 打断里面的循环 不能打断外边的循环
		if (line[i] != ' ');//skip rest of loop  if 成立时continue后面的cout << "\n" << spaces;spaces++;跳过
		continue;
		cout << "\n" << spaces;
		spaces++;
	}
	cout << "\n" << spaces << "spaces\n";
	cout << "Done.\n";
	//cin.get();
	//cin.get();

	/*int sum = 0;
	int i = 1;
	while (i <= 4)
	{
		if (i % 2 == 0)
		{
			i++;
			continue;//if 成立时continue后面的cout << "i" << i << endl;跳过
			cout << "i" << i << endl;
		}
		sum += i;
		i++;
	}
	*/
	return 0;

}

读取数字的循环

//cinfish.cpp--non-numeric input terminates loop
#include<iostream>
const int Max = 5;
int main()
{
	using namespace std;
	//get data
	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;
	while (i<Max && cin >> fish[i]) {//逻辑AND   //输入q结束输入quit
		if (i++ < Max)
			cout << "fish#" << i + 1 << ":";
	}
	//calculate average
	double total = 0.0;
	for (int j = 0;j < i;j++)
		total += fish[j];
	//report results
	if (i == 0)
		cout << total / i << "=average weight of"
		<< i << "fish\n";
	cout << "Done.\n";
	return 0;

}

读取数字循环(重置cin)

//cingolf.cpp--no-numeric input skipped
#include<iostream>
const int Max = 5;
int main()
{
	using namespace std;
	//get data
	int golf[Max];
	cout << "Please enter your golf scores.\n";
	cout << "You must enter " << Max << "rounds.\n";
	int i;
	for (i = 0;i < Max;i++)
	{
		cout << "round#" << i + 1 << ":";
		while (!(cin >> golf[i])) {
			cin.clear();//reset input重置输入
			while (cin.get() != '\n')//cin.get()读取行尾之前的所有输入,删除这一行中错误输入
				continue;//get rid of bad input
			cout << "please enter a number:";
		}
	}
	//calculate average
	double total = 0.0;
	for (i = 0;i < Max;i++)
		total += golf[i];
	//report results
	cout << total / Max << "=average score"
		<< Max << "rounds\n";
	//cin.get();
	//cin.get();
	return 0;
}

写入到文本文件中

//outfile.cpp--writing to a file
#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;//creat object for output  创建好ofstream对象outFile
	outFile.open("carinfo.txt");//associate with a file   在同一目录下 把输出的内容保存在carinfo.txt中

	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 screen with 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;

//now do exact same thing using outFile instead of cout(把cout 换成outFile)

	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();//不需要用文件名作为参数
	//cin.get();
	//cin.get();
	return 0;

}

打开文件txt 读取内容

//outfile.cpp--writing to a file
#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;//输出文件流creat object for output  创建好ofstream对象outFile
	outFile.open("carinfo.txt");//associate with a file   在同一目录下 把输出的内容保存在carinfo.txt中

	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 screen with 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;

//now do exact same thing using outFile instead of cout(把cout 换成outFile)
	//往文件carinfo.txt里写字
	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();//不需要用文件名作为参数 关闭文件
	//cin.get();
	//cin.get();

	*/

	string file("one.txt");//注意文件one 保存时 文件名 不加后缀

	//绑定文件
	//ifstream infile(file.c_str());c 语言风格
//	ifstream infile("one.txt");c++风格

	ifstream infile;//没有和一个文件绑定
	infile.open(file.c_str());//绑定文件

	//if(infile)打开文件成功
	if (!infile) {
		cerr << "error:unable to open input file:"
			<< file << endl;
		return -1;
	}
	string s;
	//infile >> s;
//	infile.close();//关掉one.txt
	while (infile >> s)//读文件 >>流输入符
		cout << s << endl;
	//cout << "读到的内容是:" << s << endl;//<<流输出符号
	return 0;

}

读取多个txt文件

#include<iostream>
#include<fstream>
#include<string>
#include<vector>

using namespace std;

void process(string s)
{
	cout << s << endl;
}
int main()
{
	vector<string>files;
	files.push_back("one.txt");
	files.push_back("carinfo.txt");//这些文件得提前存在否则出错

	string s;
	vector<string>::const_iterator it = files.begin();
	while (it != files.end())
	{
		ifstream input(it->c_str());
		if (!input)
		{
			cerr << "error:can not open file:"
				<< *it << endl;
			input.clear();//清除流
			++it;
			continue;
		}
		while (input >> s)
			process(s);
		input.close();
		++it;
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值