if语句
if (test-condition)
statement
#include <iostream>
using namespace std;
int main()
{
// if (test-condition)
// statement
char ch;
int spaces = 0;
int total = 0;
cin.get(ch);
while (ch != '.')
{
if (ch == ' ')
++spaces;
++total;
cin.get(ch); // 使用循环来输入char类型句子
}
cout << spaces << "spaces, " << total;
cout << " characters total in sentence \n";
return 0;
}
if else 语句
if else 语句
if (test-condition)
statement1
else
statement2
#include <iostream>
using namespace std;
int main()
{
// if else 语句
// if (test-condition)
// statement1
// else
// statement2
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 << "\n Please excuse the slight confusion. \n";
return 0;
}
此时输出为字符,这是因为(等价于ch = ch + 1, 没有进行类型转换)
上诉代码等价于
#include <iostream>
using namespace std;
int main()
{
// if else 语句
// if (test-condition)
// statement1
// else
// statement2
char ch;
cout << "Type, and I shall repeat. \n";
cin.get(ch);
while (ch != '.')
{
if (ch == '\n')
cout << ch;
else
{
ch = ch + 1;
cout << ch;
}
// cout << ch + 1;
cin.get(ch);
}
cout << "\n Please excuse the slight confusion. \n";
return 0;
}
若更改为
#include <iostream>
using namespace std;
int main()
{
// if else 语句
// if (test-condition)
// statement1
// else
// statement2
char ch;
cout << "Type, and I shall repeat. \n";
cin.get(ch);
while (ch != '.')
{
if (ch == '\n')
cout << ch;
else
// {
// ch = ch + 1;
// cout << ch;
// }
cout << ch + 1;
cin.get(ch);
}
cout << "\n Please excuse the slight confusion. \n";
return 0;
}
输出为整形ASCII码。(类型转换)
格式化if else语句
需要对语句块加括号,例如
if else if else 结构
if else if else 结构 一个if else 被包含在另一个if else 中。
代码
#include <iostream>
using namespace std;
int main()
{
// if else if else 结构 一个if else 被包含在另一个if else 中
int n;
const int Fave = 27;
cout << "Enter a number in the range of 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;
}
逻辑表达式
OR操作符:||
例子:
只要有一个为true则整体为true
顺序点:
代码
#include <iostream>
using namespace std;
int main()
{
// 逻辑运算符 OR (||), AND(&&), NOT(!)
// 逻辑运算符的优先级比关系运算符低
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 are warned!\a\a\n";
else if (ch == 'n' || ch == 'N')
cout << "A wise choice ... bye \n";
else
cout << "That wasn't a y or an n, so I guess I'll "
"trash your disk anyway.\a\a\n";
return 0;
}
AND操作符: &&
当且仅当两个都为true时候整体才为true(有一个错则全错)
例子
#include <iostream>
using namespace std;
int main()
{
const int ArSize = 6;
float naaq[ArSize];
cout << "Enter the NAAQs (New Age Awareness Quotient)"
<< "of \n your neighbors. Program terminate "
<< "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;
}
&& 来设置取值范围
#include <iostream>
using namespace std;
int main()
{
//&& 来设置取值范围
// list 6.6
const char *qualify[4] =
{
"10, 000-meter race, \n",
"mud tug-of-war.\n",
"masters canoe jousting.\n",
"pie-throwing festival. \n"};
int age;
cout << "Enter your age in years: ",
cin >> age;
int index;
if (age > 17 && age < 35) // 使用if else 控制范围
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;
}
NOT操作符:!
#include <iostream>
bool is_int(double);
using namespace std;
int main()
{
double num;
cout << "Yo, dude! Enter an integer value: ";
cin >> num;
while (!is_int(num)) // 在int范围内 函数输出true, 取反为false退出循环
{
cout << "Out of range -- please try again: ";
cin >> num;
}
int val = int(num);
cout << "You've entered the integer " << val << "\nBye\n";
return 0;
// 优先级 AND(&&) > OR(||), !的优先级最高。
}
bool is_int(double x)
{
if (x <= INT_MAX && x >= INT_MIN)
return true;
else
return false;
}
使用了一个返回类型为bool的函数
字符函数库cctype
#include <iostream>
using namespace std;
int main()
{
// 头文件cctype isalpha(ch) 判断是否为字母,是的话输出为true
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))
punct++;
else
others++;
cin.get(ch);
}
cout << chars << " Letters, "
<< whitespace << " whitespace, "
<< digits << " digits, "
<< punct << " punctuations, "
<< others << " others. \n";
return 0;
}
?操作符
?操作符 需要三个操作数的操作符
expression1 ? expression2 : expression3
if the expression1 is true, return expression2, else return expression3;
使用条件操作符确定两个值中较大的一个:
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;
cout << " is " << c << endl;
return 0;
}
其实等价于if else 语句。
switch语句
switch
switch (integer-expression)
{
case label1 : statement(s)
case label1 : statement(s)
...
default : statement(s)
}
常见的标签有 int 和 char 类型,或者是枚举量;switch 将执行之后的所有语句
de <iostream>
using namespace std;
void show_menu();
void report();
void comfort();
int main()
{
int choice;
show_menu();
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";
}
show_menu();
cin >> choice;
}
cout << "Bye!\n";
return 0;
}
void show_menu()
{
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";
}
将枚举量用作标签
#include <iostream>
using namespace std;
void show_menu();
void report();
void comfort();
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:
case orange:
cout << "Her hair was orange. \n";
break;
case yellow:
cout << "Her shoes were yellow. \n";
break;
case green:
cout << "Her nails were green. \n";
break;
case blue:
cout << "Her sweatsuit was blue. \n";
break;
case violet:
cout << "Her eyes were violet.\n";
break;
case indigo:
cout << "Her mood was indigo.\n";
break;
}
cout << "Enter color code (0-6): ";
cin >> code;
}
cout << "Bye\n";
return 0;
// // switch 和 if else 的功能类似,但是switch 无法处理浮点测试
}
break 和 continue 语句
break 直接跳出循环,进行之后的一语句;
continue 跳过当前的循环体,进入下一轮循环。
#include <iostream>
using namespace std;
const int ArSize = 80;
int main()
{
// break 直接跳出循环,进行之后的一语句;
// continue 跳过当前的循环体,进入下一轮循环。
// list 6.12
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;
}
读取数字的循环
#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;
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;
}
当程序发现错误是,应采取三步
#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";
int i;
for (i = 0; i < Max; i++)
{
cout << "round #" << i + 1 << ": ";
while (!(cin >> golf[i])) // 当输入cin 出错时,进入下面的循环
{
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;
}
简单文件输入/输出
文本I/O 和文本文件
写入到文本文件中
文件输入的准备工作(类比cout输出)
总的来说
#include <iostream>
#include <fstream> // file I/O support
using namespace std;
int main()
{
// list 6.15
char automobile[50];
int year;
double a_price;
double d_price;
ofstream outFile; // create object for output
outFile.open("carinfo.text"); // 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;
//
cout << fixed;
cout.precision(2); // use a precision of 2 for the display
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;
//
outFile << fixed;
outFile.precision(2); // use a precision of 2 for the output
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();
return 0;
}
读取文本文件
cin 本身作为测试条件式,如果读取正确则操作成功,转换为true.
iostream 提供了一个预先定义好的cin的istream对象,如果要声明自己的ifstream必须要向命名,
ifstream inFile; // inFile an ifstream object
ifstream fin; // fin a ifstream object
// 对象和文件关联起来
inFile.open("bowling.txt"); //inFile used to read bowling.txt file
char filename(50);
cin >> filename; // user specifies a name
fin.open(filename); //fin used to read specified file
open()方法接受一个C风格字符串作为参数,可以是一个字面字符串,也可以是一个存储在数组中的字符串。
例如对下列文件的读取
using namespace std;
int main()
{
// list 6.16
char filename[SiZE];
ifstream inFile;
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 // 检查文件是否打开十分重要
{
cout << "Could not open the file " << filename << endl;
cout << "Program terminating.\n";
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 reach.\n";
else if (inFile.fail())
cout << "Input terminated by dta mismatch. \n";
else
cout << "Input terminate 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;
}